This tutorial will take you through many of the steps you would need to add PayPal payments to an ASP.NET web application. It does not however link the transactions with database - something you would need to do for a completed system.
You can see further examples within the PayPal REST API reference (be sure to set the language to C#) and the Sample code for creating a PayPal payment using ASP.NET.
To complete this tutorial, you need to have registered with PayPal and setup a developer account, as well as having created a 'REST API app' in the developer dashboard. You will need a Client ID and Secret for the Sandbox. You must use the Sandbox for this tutorial, otherwise you could end up making real payments
You will also need test buyer accounts for the sandbox which will give you an email address as password to use when testing payments
<h2>Purchase past exam questions</h2>
<asp:Label ID="lblQuantity" runat="server" Text="Quantity at £10 each" AssociatedControlID="ddlExamQuantity"></asp:Label>
<asp:DropDownList ID="ddlExamQuantity" runat="server">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
</asp:DropDownList>
<p>Postage and packaging charges of £3.95 will be applied to your order</p>
<asp:Button ID="btnPurchaseExamQuestions" runat="server" Text="Buy Now" />
protected void btnPurchaseExamQuestions_Click(object sender, EventArgs e)
{
decimal postagePackingCost = 3.95m;
decimal examPaperPrice = 10.00m;
int quantityOfExamPapers = int.Parse(ddlExamQuantity.SelectedValue);
decimal subtotal = (quantityOfExamPapers * examPaperPrice);
decimal total = subtotal + postagePackingCost;
}
In order to use PayPal, we need to add the PayPal API to our project. We can do this in one step by using the NuGet Package Manager.
<configuration>
section add the following code, amending the clientId and clientSecret values to those from your PayPal Sandbox API credentials:
<configSections>
<section name="paypal" type="PayPal.SDKConfigHandler, PayPal" />
</configSections>
<paypal>
<settings>
<add name="mode" value="sandbox" />
<add name="clientId" value="YOUR_CLIENT_ID" />
<add name="clientSecret" value="YOUR_CLIENT_SECRET" />
</settings>
</paypal>
using
statement, add the following line of code: using PayPal.Api;
// Authenticate with PayPal
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
//Get APIContext Object
var apiContext = new APIContext(accessToken);
The next step is to create an 'Item' which will refer to a particular product to be purchased, along with its price, currency, quantity and SKU (Stock Keeping Unit, for example a manufacturer code or model number). Because the data will be sent as a standard HTTP request, numeric values need to be converted to strings. In this example we are only creating one item, but it would be possible to have multiple items in the transaction
Add the following code to create the Item:var examPaperItem = new Item();
examPaperItem.name = "Past Exam Paper";
examPaperItem.currency = "GBP";
examPaperItem.price = examPaperPrice.ToString();
examPaperItem.sku = "PEPCO5027m15"; //sku is stock keeping unit - e.g. manufacturer code
examPaperItem.quantity = quantityOfExamPapers.ToString();
var transactionDetails = new Details();
transactionDetails.tax = "0";
transactionDetails.shipping = postagePackingCost.ToString();
transactionDetails.subtotal = subtotal.ToString("0.00");
var transactionAmount = new Amount();
transactionAmount.currency = "GBP";
transactionAmount.total = total.ToString("0.00");
transactionAmount.details = transactionDetails;
var transaction = new Transaction();
transaction.description = "Your order of Past Exam papers";
transaction.invoice_number = Guid.NewGuid().ToString(); //this should ideally be the id of a record storing the order
transaction.amount = transactionAmount;
transaction.item_list = new ItemList
{
items = new List<Item> { examPaperItem }
};
var payer = new Payer();
payer.payment_method = "paypal";
RedirectUrls
object. Add the following code and create appropriately named pages in your project so redirected users do not see a 404 error:
var redirectUrls = new RedirectUrls();
redirectUrls.cancel_url = "http://localhost:2506/Cancel.aspx";
redirectUrls.return_url = "http://localhost:2506/CompletePurchase.aspx";
var payment = Payment.Create(apiContext, new Payment
{
intent = "sale",
payer = payer,
transactions = new List<Transaction> { transaction },
redirect_urls = redirectUrls
});
Session["paymentId"] = payment.id;
foreach (var link in payment.links)
{
if (link.rel.ToLower().Trim().Equals("approval_url"))
{
//found the appropriate link, send the user there
Response.Redirect(link.href);
}
}
<h2>Complete Your Purchase</h2>
<asp:Button ID="btnConfirmPurchase" runat="server" Text="Confirm" />
<asp:Literal ID="litInformation" runat="server"></asp:Literal>
using PayPal.Api;
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);
var paymentId = Session["paymentId"].ToString();
if (!String.IsNullOrEmpty(paymentId))
{
//create a payment object with the paymentId from session
var payment = new Payment() { id = paymentId };
}
if
statement:
//retrieve the payerId from the querystring and use it to create a new payment execution object
var payerId = Request.QueryString["PayerID"].ToString();
var paymentExecution = new PaymentExecution() { payer_id = payerId };
//execute the payment
var executedPayment = payment.Execute(apiContext, paymentExecution);
//inform the user
litInformation.Text = "<p>Your order has been completed</p>";
btnConfirmPurchase.Visible = false;