Skip to content

Instantly share code, notes, and snippets.

@james-dibble
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save james-dibble/8801628 to your computer and use it in GitHub Desktop.

Select an option

Save james-dibble/8801628 to your computer and use it in GitHub Desktop.
An example MVC controller for interacting with a PayPal payment service
namespace TheBush.Controllers
{
using System.Globalization;
using System.IO;
using System.Web.Mvc;
using PayPal.Exception;
using Application.Services;
using System.Linq;
using global::PayPal.Api.Payments;
public class ShoppingCartController : Controller
{
private readonly IPaymentService _paymentService;
public ActionResult Purchase()
{
var baseUrl = string.Concat(this.Request.Url.Scheme, "://", this.Request.Url.Authority);
try
{
var order = // Retrieve/create your order object somehow
var cancelUrl = this.Url.Action("purchaseunsucessful", "order");
var returnUrl = this.Url.Action("purchasecomplete", "order", new { orderNumber = order.OrderNumber.ToLower() });
var payment = this._paymentService.CreatePayment(order, string.Concat(baseUrl, cancelUrl), string.Concat(baseUrl, returnUrl));
if (!payment.WasCreated())
{
return this.RedirectToAction("purchaseunsucessful");
}
// Save order with payment.id somewhere on it
return this.Redirect(payment.GetApprovalUrl());
}
catch (PayPalException ex)
{
this.ViewBag.Error = ((ConnectionException)ex.InnerException).Response;
}
catch (Exception ex)
{
this.ViewBag.Error = ex.Message;
}
return this.RedirectToAction("purchaseunsucessful");
}
public ActionResult PurchaseUnsucessful()
{
return this.View();
}
public ActionResult PurchaseComplete(string orderNumber, string payerId)
{
try
{
var order = // Retrieve the order using the order number we saved into the returnUrl
this._paymentService.ConfirmPayment(order.PaymentReference, payerId, order);
return this.View("purchasecomplete", order);
}
catch (PayPalException ex)
{
this.ViewBag.Error = ((ConnectionException)ex.InnerException).Response;
}
catch (Exception ex)
{
this.ViewBag.Error = ex.Message;
}
return this.RedirectToAction("purchaseunsucessful");
}
}
public static class PaymentExtensions
{
public static string GetApprovalUrl(this Payment payment)
{
return payment.links.First(link => link.rel.ToLowerInvariant() == "approval_url".ToLowerInvariant()).href;
}
public static bool WasSucessful(this Payment payment)
{
return payment.state.ToLowerInvariant() == "approved";
}
public static bool WasCreated(this Payment payment)
{
return payment.state.ToLowerInvariant() == "created";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment