Sunday, February 22, 2009

How to Integration PayPal With ASP.NET C#

Hi
I have Integration Paypal Payment System to our website.When i got the job I don't have Any exprence to develope any payment system.I face somany Problem to intregate that systen.
So i am writing this bloge for the new devloper who is willing to Develop Paypel system with ASP.NET C#.
2a. Insert this code snippet into the section of your code that handles shopping cart.*

2b. Create these files to your shopping cart web directory
expresscheckout.aspx


expresscheckout.aspx.cs
using System;
using System.Web;
public partial class PayPalEC : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
NVPAPICaller test = new NVPAPICaller();
string retMsg = "";
string token = "";

if ( Session["payment_amt"] != null)
{
string amt = Session["payment_amt"].ToString();
bool ret = test.ShortcutExpressCheckout(amt, ref token, ref retMsg);
if (ret)
{
Session["token"] = token;
Response.Redirect( retMsg );
}
else
{
Response.Redirect("APIError.aspx?" + retMsg);
}
}
else
{
Response.Redirect( "APIError.aspx?ErrorCode=AmtMissing" );
}
}
}
APIError.aspx.cs


paypalfunctions.cs ( Please save this file into the AppCode sub directory of your .Net web app )

using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
using System.Data;
using System.Configuration;
using System.Web;

///
/// Summary description for NVPAPICaller
///

public class NVPAPICaller
{
//private static readonly ILog log = LogManager.GetLogger(typeof(NVPAPICaller));

private string pendpointurl = "https://api-3t.paypal.com/nvp";
private const string CVV2 = "CVV2";

//Flag that determines the PayPal environment (live or sandbox)
private const bool bSandbox = true;

private const string SIGNATURE = "SIGNATURE";
private const string PWD = "PWD";
private const string ACCT = "ACCT";

public string APIUsername = "YourAPIUsername ";
private string APIPassword = "YourAPIPassword ";
private string APISignature = "YourSignature ";
private string Subject = "";
private string BNCode = "PP-ECWizard";

//HttpWebRequest Timeout specified in milliseconds
private const int Timeout = 5000;
private static readonly string[] SECURED_NVPS = new string[] { ACCT, CVV2, SIGNATURE, PWD };


///
/// Sets the API Credentials
///

///
///
///
///
public void SetCredentials(string Userid, string Pwd, string Signature)
{
APIUsername = Userid;
APIPassword = Pwd;
APISignature = Signature;
}

///
/// ShortcutExpressCheckout: The method that calls SetExpressCheckout API
///

///
///
///
///
public bool ShortcutExpressCheckout(string amt, ref string token, ref string retMsg)
{
string host = "www.paypal.com";
if (bSandbox)
{
pendpointurl = "https://api-3t.sandbox.paypal.com/nvp";
host = "www.sandbox.paypal.com";
}

string returnURL = "http://www.yourstore.com/OrderConfirmPage.aspx";
string cancelURL = "http://wwww.yourstore.com/MainPage.aspx";

NVPCodec encoder = new NVPCodec();
encoder["METHOD"] = "SetExpressCheckout";
encoder["RETURNURL"] = returnURL;
encoder["CANCELURL"] = cancelURL;
encoder["AMT"] = amt;
encoder["PAYMENTACTION"] = "Sale";
encoder["CURRENCYCODE"] = "USD";

string pStrrequestforNvp = encoder.Encode();
string pStresponsenvp = HttpCall(pStrrequestforNvp);

NVPCodec decoder = new NVPCodec();
decoder.Decode(pStresponsenvp);

string strAck = decoder["ACK"].ToLower();
if (strAck != null && (strAck == "success" strAck == "successwithwarning"))
{
token = decoder["TOKEN"];

string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout&" + "&token=" + token;

retMsg = ECURL;
return true;
}
else
{
retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
"Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
"Desc2=" + decoder["L_LONGMESSAGE0"];

return false;
}
}

///
/// MarkExpressCheckout: The method that calls SetExpressCheckout API, invoked from the
/// Billing Page EC placement
///

///
///
///
///
public bool MarkExpressCheckout(string amt,
string shipToName, string shipToStreet, string shipToStreet2,
string shipToCity, string shipToState, string shipToZip,
string shipToCountryCode,ref string token, ref string retMsg)
{
string host = "www.paypal.com";
if (bSandbox)
{
pendpointurl = "https://api-3t.sandbox.paypal.com/nvp";
host = "www.sandbox.paypal.com";
}

string returnURL = "http://www.yourstore.com/OrderConfirmPage.aspx";
string cancelURL = "http://wwww.yourstore.com/MainPage.aspx";

NVPCodec encoder = new NVPCodec();
encoder["METHOD"] = "SetExpressCheckout";
encoder["RETURNURL"] = returnURL;
encoder["CANCELURL"] = cancelURL;
encoder["AMT"] = amt;
encoder["PAYMENTACTION"] = "Sale";
encoder["CURRENCYCODE"] = "USD";

//Optional Shipping Address entered on the merchant site
encoder["SHIPTONAME"] = shipToName;
encoder["SHIPTOSTREET"] = shipToStreet;
encoder["SHIPTOSTREET2"] = shipToStreet2;
encoder["SHIPTOCITY"] = shipToCity;
encoder["SHIPTOSTATE"] = shipToState;
encoder["SHIPTOZIP"] = shipToZip;
encoder["SHIPTOCOUNTRYCODE"]= shipToCountryCode;


string pStrrequestforNvp = encoder.Encode();
string pStresponsenvp = HttpCall(pStrrequestforNvp);

NVPCodec decoder = new NVPCodec();
decoder.Decode(pStresponsenvp);

string strAck = decoder["ACK"].ToLower();
if (strAck != null && (strAck == "success" strAck == "successwithwarning"))
{
token = decoder["TOKEN"];

string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout&" + "&token=" + token;

retMsg = ECURL;
return true;
}
else
{
retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
"Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
"Desc2=" + decoder["L_LONGMESSAGE0"];

return false;
}
}



///
/// GetShippingDetails: The method that calls SetExpressCheckout API, invoked from the
/// Billing Page EC placement
///

///
///
///
public bool GetShippingDetails(string token, ref string PayerId, ref string ShippingAddress, ref string retMsg)
{

if (bSandbox)
{
pendpointurl = "https://api-3t.sandbox.paypal.com/nvp";
}

NVPCodec encoder = new NVPCodec();
encoder["METHOD"] = "GetExpressCheckoutDetails";
encoder["TOKEN"] = token;

string pStrrequestforNvp = encoder.Encode();
string pStresponsenvp = HttpCall( pStrrequestforNvp );

NVPCodec decoder = new NVPCodec();
decoder.Decode( pStresponsenvp );

string strAck = decoder["ACK"].ToLower();
if (strAck != null && (strAck == "success" strAck == "successwithwarning"))
{
ShippingAddress = " ";
ShippingAddress += " ";
ShippingAddress += " ";
ShippingAddress += " ";
ShippingAddress += " ";
ShippingAddress += " ";
ShippingAddress += " ";
ShippingAddress += " ";
ShippingAddress += " ";
ShippingAddress += " ";
ShippingAddress += "";

return true;
}
else
{
retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
"Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
"Desc2=" + decoder["L_LONGMESSAGE0"];

return false;
}
}


///
/// ConfirmPayment: The method that calls SetExpressCheckout API, invoked from the
/// Billing Page EC placement
///

///
///
///
public bool ConfirmPayment(string finalPaymentAmount, string token, string PayerId, ref NVPCodec decoder, ref string retMsg )
{
if (bSandbox)
{
pendpointurl = "https://api-3t.sandbox.paypal.com/nvp";
}

NVPCodec encoder = new NVPCodec();
encoder["METHOD"] = "DoExpressCheckoutPayment";
encoder["TOKEN"] = token;
encoder["PAYMENTACTION"] = "Sale";
encoder["PAYERID"] = PayerId;
encoder["AMT"] = finalPaymentAmount;

string pStrrequestforNvp = encoder.Encode();
string pStresponsenvp = HttpCall(pStrrequestforNvp);

decoder = new NVPCodec();
decoder.Decode(pStresponsenvp);

string strAck = decoder["ACK"].ToLower();
if (strAck != null && (strAck == "success" strAck == "successwithwarning"))
{
return true;
}
else
{
retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
"Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
"Desc2=" + decoder["L_LONGMESSAGE0"];

return false;
}
}


///
/// HttpCall: The main method that is used for all API calls
///

///
///
public string HttpCall(string NvpRequest) //CallNvpServer
{
string url = pendpointurl;

//To Add the credentials from the profile
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + UrlEncode( BNCode );

HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;

try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost);
}
}
catch (Exception e)
{
/*
if (log.IsFatalEnabled)
{
log.Fatal(e.Message, this);
}*/
}

//Retrieve the Response returned from the NVP API call to PayPal
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}

//Logging the response of the transaction
/* if (log.IsInfoEnabled)
{
log.Info("Result :" +
" Elapsed Time : " + (DateTime.Now - startDate).Milliseconds + " ms" +
result);
}
*/
return result;
}

///
/// Credentials added to the NVP string
///

///
///
private string buildCredentialsNVPString()
{
NVPCodec codec = new NVPCodec();

if (!IsEmpty(APIUsername))
codec["USER"] = APIUsername;

if (!IsEmpty(APIPassword))
codec[PWD] = APIPassword;

if (!IsEmpty(APISignature))
codec[SIGNATURE] = APISignature;

if (!IsEmpty(Subject))
codec["SUBJECT"] = Subject;

codec["VERSION"] = "2.3";

return codec.Encode();
}

///
/// Returns if a string is empty or null
///

/// the string
/// true if the string is not null and is not empty or just whitespace
public static bool IsEmpty(string s)
{
return s == null s.Trim() == string.Empty;
}
}


public sealed class NVPCodec : NameValueCollection
{
private const string AMPERSAND = "&";
private const string EQUALS = "=";
private static readonly char[] AMPERSAND_CHAR_ARRAY = AMPERSAND.ToCharArray();
private static readonly char[] EQUALS_CHAR_ARRAY = EQUALS.ToCharArray();

///
/// Returns the built NVP string of all name/value pairs in the Hashtable
///

///
public string Encode()
{
StringBuilder sb = new StringBuilder();
bool firstPair = true;
foreach (string kv in AllKeys)
{
string name = UrlEncode(kv);
string value = UrlEncode(this[kv]);
if (!firstPair)
{
sb.Append(AMPERSAND);
}
sb.Append(name).Append(EQUALS).Append(value);
firstPair = false;
}
return sb.ToString();
}

///
/// Decoding the string
///

///
public void Decode(string nvpstring)
{
Clear();
foreach (string nvp in nvpstring.Split(AMPERSAND_CHAR_ARRAY))
{
string[] tokens = nvp.Split(EQUALS_CHAR_ARRAY);
if (tokens.Length >= 2)
{
string name = UrlDecode(tokens[0]);
string value = UrlDecode(tokens[1]);
Add(name, value);
}
}
}

private static string UrlDecode(string s) { return HttpUtility.UrlDecode(s); }
private static string UrlEncode(string s) { return HttpUtility.UrlEncode(s); }

#region Array methods
public void Add(string name, string value, int index)
{
this.Add(GetArrayName(index, name), value);
}

public void Remove(string arrayName, int index)
{
this.Remove(GetArrayName(index, arrayName));
}

///
///
///

public string this[string name, int index]
{
get
{
return this[GetArrayName(index, name)];
}
set
{
this[GetArrayName(index, name)] = value;
}
}

private static string GetArrayName(int index, string name)
{
if (index <>
First Name " + decoder["FIRSTNAME"] + "
Last Name " + decoder["LASTNAME"] + "
Shipping Address
Name " + decoder["SHIPTONAME"] + "
Street1 " + decoder["SHIPTOSTREET"] + "
Street2 " + decoder["SHIPTOSTREET2"] + "
City " + decoder["SHIPTOCITY"] + "
State " + decoder["SHIPTOSTATE"] + "
Zip " + decoder["SHIPTOZIP"] + "


Insert this code snippet into the section of your code that handles billing
if (PaymentOption == "PayPal")
{
NVPAPICaller test = new NVPAPICaller();

string retMsg = "";
string token = "";

if (Session["payment_amt"] != null)
{
string amt = Session["payment_amt"].ToString();

//Optional Shipping Address entered on the merchant site
string shipToName = "";
string shiptToStreet = "";
string shiptToStreet2 = "";
string shipToCity = "";
string shipToState = "";
string shipToZip = "";
string shipToCountryCode = "";

bool ret = test.MarkExpressCheckout(amt, shipToName, shipToStreet, shipToStreet2,
shipToCity, shipToState, shipToZip, shipToCountryCode,
ref token, ref retMsg);
if (ret)
{
Session["token"] = token;
Response.Redirect(retMsg);
}
else
{
Response.Redirect("APIError.aspx?" + retMsg);
}
}
else
{
Response.Redirect( "APIError.aspx?ErrorCode=AmtMissing" );
}
}

To pass the shipping address entered, replaced the shipping address placeholders in the code snippet with variables representing the shipping address from PayPal.

Save the total payment amount in a session variable named "Payment_Amount". The code inside the ExpressCheckout file is designed to read from this session variable and pass as input to the API call.

Order Review - get shipping address from PayPal
Insert this code snippet into the section of your code that handles order review

if (PaymentOption == "PayPal"){ NVPAPICaller test = new NVPAPICaller();
string retMsg = ""; string token = ""; string payerId = "";
token = Session["token"].ToString();
bool ret = test.GetShippingDetails( token, ref payerId, ref shippingAddress, ref retMsg ); if (ret) { Session["payerId"] = payerId; Response.Write ( shippingAddress ); } else { Response.Redirect("APIError.aspx?" + retMsg); }}



Save the total payment amount in a session variable named "Payment_Amount". The code inside the ExpressCheckout file is designed to read from this session variable and pass as input to the API call

Order Confirmation - confirm payment from PayPal
Insert this code snippet into the section of your code that handles order confirmation.
if (PaymentOption == "PayPal"){ NVPAPICaller test = new NVPAPICaller();
string retMsg = ""; string token = ""; string finalPaymentAmount = ""; string payerId = ""; NVPCodec decoder;
token = Session["token"].ToString(); payerId = Session["payerId"].ToString(); finalPaymentAmount = Session["payment_amt"].ToString();
bool ret = test.ConfirmPayment( finalPaymentAmount, token, PayerId, ref decoder, ref retMsg ); if (ret) { // Unique transaction ID of the payment. Note: If the PaymentAction of the request was Authorization or Order, this value is your AuthorizationID for use with the Authorization & Capture APIs. string transactionId = decoder["TRANSACTIONID"];
// The type of transaction Possible values: l cart l express-checkout string transactionType = decoder["TRANSACTIONTYPE"];
// Indicates whether the payment is instant or delayed. Possible values: l none l echeck l instant string paymentType = decoder["PAYMENTTYPE"];
// Time/date stamp of payment string orderTime = decoder["ORDERTIME"];
// The final amount charged, including any shipping and taxes from your Merchant Profile. string amt = decoder["AMT"];
// A three-character currency code for one of the currencies listed in PayPay-Supported Transactional Currencies. Default: USD. string currencyCode = decoder["CURRENCYCODE"]; // PayPal fee amount charged for the transaction string feeAmt = decoder["FEEAMT"];
// Amount deposited in your PayPal account after a currency conversion. string settleAmt = decoder["SETTLEAMT"];
// Tax charged on the transaction. string taxAmt = decoder["TAXAMT"];
//' Exchange rate if a currency conversion occurred. Relevant only if your are billing in their non-primary currency. If string exchangeRate = decoder["EXCHANGERATE"]; } else { Response.Redirect("APIError.aspx?" + retMsg); }}