This is one of the common problems where while building an e-commerce portal we need to provide paypal payment support. In this post we will look into how we can do the express checkout using a paypal checkout button and then taking the user to paypal to authenticate the payment and then processing the payment followed by its notification. All the code will be in C# and its a working and tested code on Sandbox.
Visit https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_ECGettingStarted to know what will be achieved as the outcome of this exercise.
Following are the steps to be followed in the Paypal payment development:
1) Sandbox Account creation and setup
2) Choosing one of the Paypal API interaction way, In this case its using SOAP services.
3) C# code and ASP.NET page code to initiate and complete the process.
We will now look closely into what I mean with each of these:
1) Sandbox Account Creation and Setup
Visit https://developer.paypal.com and create an account which will be your developer account using which we will create account simulators or role play users.
Once this is done, log into https://developer.paypal.com and start creating Test Accounts using Pre-Configured account. Provide the details asked and create Buyer, Seller and Pro accounts so that we can test it by playing these roles.
Accounts are now set and we can proceed with the coding and executing it.
2) The API interaction way we chose here is SOAP service. Since VS has a very good WSDL parser hence went through with this way and in your solution or web project add a reference to https://www.sandbox.paypal.com/wsdl/PayPalSvc.wsdl and give it some name like PaypalSandboxService
We are now ready to consume it on our page and see it working.
3) Coding and using it on our page:
Here is aspx page with Checkout button:
<asp:ImageButton runat="server" ID="btnPaypal" AlternateText="checkout with paypal" ImageUrl="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif" />
This will show the checkout with Paypal button on the page. Below is the onClick event handler code:
void btnPaypal_Click(object sender, ImageClickEventArgs e)
{
CustomSecurityHeaderType type = new CustomSecurityHeaderType();
type.Credentials = new UserIdPasswordType()
{
Username = "xxxxx_123123123_biz_api1.gmail.com",
Password = "--------",
Signature = "AFcWxV21C7fd0v3bYYYRCpSSRl31A65G85Y3c.28ROij7FUFefzBgM02"
};
SetExpressCheckoutRequestDetailsType sdt = new SetExpressCheckoutRequestDetailsType();
sdt.NoShipping = "1";
PaymentDetailsType pdt = new PaymentDetailsType()
{
OrderDescription = "Payment Details Sushant",
OrderTotal = new BasicAmountType()
{
currencyID = CurrencyCodeType.USD,
Value = "100.00"
}
};
sdt.PaymentDetails = new PaymentDetailsType[] { pdt };
sdt.CancelURL = "http://localhost:56980/Default.aspx";
sdt.ReturnURL = "http://localhost:56980/ExpressCheckoutSuccess.aspx";
SetExpressCheckoutReq req = new SetExpressCheckoutReq()
{
SetExpressCheckoutRequest = new SetExpressCheckoutRequestType()
{
SetExpressCheckoutRequestDetails = sdt,
Version = "60.0"
}
};
var resp = paypalAAInt.SetExpressCheckout(ref type, req);
if (resp.Errors != null && resp.Errors.Length > 0)
{
// errors occured
throw new Exception("Exception(s) occured when calling PayPal. First exception: " +
resp.Errors[0].LongMessage);
}
Response.Redirect(string.Format("{0}?cmd=_express-checkout&token={1}",
ConfigurationManager.AppSettings["PayPalSubmitUrl"], resp.Token));
}
here paypal submit url looks like: <add key="PayPalSubmitUrl" value="https://www.sandbox.paypal.com/cgi-bin/webscr"/> in the web.config appsettings.
The ExpressCheckoutSuccess page is when the authentication at Paypal is successful and we want the user to do a final review and click on the Finish to get the actual transaction take place. For this we will show below the code of Express Checkout success page:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ExpressCheckoutSuccess.aspx.cs" Inherits="RYOARS.Web.ExpressCheckoutSuccess" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:Button ID="finishTransactionButton" runat="server"
Text="Finish transaction!" onclick="finishTransactionButton_Click" />
</div>
</form>
</body>
</html>
and the C# code behind will look like in this case:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RYOARS.Web.PaypalSandboxService;
namespace RYOARS.Web
{
public partial class ExpressCheckoutSuccess : System.Web.UI.Page
{
PayPalAPIAAInterfaceClient client = new PayPalAPIAAInterfaceClient();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string token = Request.QueryString["token"];
CustomSecurityHeaderType type = new CustomSecurityHeaderType();
type.Credentials = new UserIdPasswordType()
{
Username = "xxxxx_123123123_biz_api1.gmail.com",
Password = "---------",
Signature = "AFcWxV21C7fd0v3bYYYRCpSSRl31A65G85Y3c.28ROij7FUFefzBgM02"
};
// build getdetails request
GetExpressCheckoutDetailsReq req = new GetExpressCheckoutDetailsReq()
{
GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType()
{
Version = "60.0",
Token = token
}
};
// query PayPal for transaction details
GetExpressCheckoutDetailsResponseType resp =
client.GetExpressCheckoutDetails(ref type, req);
//UtilPayPalAPI.HandleError(resp);
if (resp.Errors != null && resp.Errors.Length > 0)
{
// errors occured
throw new Exception("Exception(s) occured when calling PayPal. First exception: " +
resp.Errors[0].LongMessage);
}
GetExpressCheckoutDetailsResponseDetailsType respDetails = resp.GetExpressCheckoutDetailsResponseDetails;
// setup UI and save transaction details to session
Label1.Text = string.Format(
"Dear {0} {1}, everything is set for {2} {3} transaction to take place. Click on button below to commit transaction",
respDetails.PayerInfo.PayerName.FirstName,
respDetails.PayerInfo.PayerName.LastName,
respDetails.PaymentDetails[0].OrderTotal.Value,
respDetails.PaymentDetails[0].OrderTotal.currencyID
);
Session["CheckoutDetails"] = resp;
}
}
protected void finishTransactionButton_Click(object sender, EventArgs e)
{
// get transaction details
GetExpressCheckoutDetailsResponseType resp = Session["CheckoutDetails"] as GetExpressCheckoutDetailsResponseType;
CustomSecurityHeaderType type = new CustomSecurityHeaderType();
type.Credentials = new UserIdPasswordType()
{
Username = "xxxxx_123123123_biz_api1.gmail.com",
Password = "--------",
Signature = "AFcWxV21C7fd0v3bYYYRCpSSRl31A65G85Y3c.28ROij7FUFefzBgM02"
};
// prepare for commiting transaction
DoExpressCheckoutPaymentReq payReq = new DoExpressCheckoutPaymentReq()
{
DoExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType()
{
Version = "60.0",
DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType()
{
Token = resp.GetExpressCheckoutDetailsResponseDetails.Token,
PaymentAction = PaymentActionCodeType.Sale,
PaymentActionSpecified = true,
PayerID = resp.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID,
PaymentDetails = new PaymentDetailsType[] {
new PaymentDetailsType()
{
OrderTotal = new BasicAmountType()
{
currencyID = CurrencyCodeType.USD,
Value = "100.0"
}
}
}
}
}
};
// commit transaction and display results to user
DoExpressCheckoutPaymentResponseType doResponse =
client.DoExpressCheckoutPayment(ref type, payReq);
if (doResponse.Errors != null && doResponse.Errors.Length > 0)
{
// errors occured
throw new Exception("Exception(s) occured when calling PayPal. First exception: " +
doResponse.Errors[0].LongMessage);
}
Label1.Text = "Payment was successfully processed!";
finishTransactionButton.Visible = false;
}
}
}
Now, you code is ready to go and work fine. We have tested this with our test account and it works just smoothly. So, its very easy to integrate paypal express checkout in your page.
We will also look into Direct payment where your code behind or C# need to directly need to charge a customer based on its information and when certain condition is met. We will look into this in the next post on the same line.
Till then, try this one!!
- bye for now
4aefcdc2-69de-4bb8-97ab-283c7a537393|1|5.0
Categories:
ASP.NET, C#, Paypal
7. November 2011
Tags:
Paypal payment, express checkout, C# payment, C# gateway, paypal integration