Paypal支付API接口支付的流程有创建订单,待用户支付,获取用户授权的订单入账!

我们案例做的是用户打赏功能,即用户点击文章下面的打赏,我们便调用Paypal支付API接口引导用户支付。


用户点击打赏,系统会调用C#后台的打赏接口:https://www.pupilshome.com/a/dashang/id,打赏接口内部会调用Palpal API创建订单,具体实现代码

[HttpGet]
public ActionResult Dashang(string id)
{
List<Item> itms = new List<Item>() { new Item() { name = "文章打赏", currency = "USD", price = "1", sku = "piece", quantity = "1" } };
ItemList itemList = new ItemList() { items = itms };
Payer payr = new Payer() { payment_method = "paypal" };
string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/a/orderschange";
RedirectUrls redirUrls = new RedirectUrls() { return_url = baseURI };
redirUrls.cancel_url = Request.UrlReferrer == null ? baseURI : Request.UrlReferrer.ToString();
double itmsTotal = 0;
foreach (var itm in itms) { itmsTotal += (itm.price.ToDouble() ?? 0) * (itm.quantity.ToInt() ?? 0); }
Details details = new Details() { tax = "0", shipping = "0", subtotal = itmsTotal.ToString() };
Amount amnt = new Amount() { currency = itms.FirstOrDefault().currency, details = details };
amnt.total = ((int)details.subtotal.ToInt() + (int)details.tax.ToInt() + (int)details.shipping.ToInt()).ToString();
Transaction tran = new Transaction() { description = "文章打赏1USD,谢谢您!", amount = amnt, item_list = itemList };
List<Transaction> transactionList = new List<Transaction>() { tran };
var pymnt = new Payment() { intent = "sale", payer = payr, transactions = transactionList, redirect_urls = redirUrls };
try
{
    string approvalUrl = "";
    pymnt = pymnt.Create(PayPalAPIContext);
    var links = pymnt.links.GetEnumerator();
    while (links.MoveNext())
    {
        Links lnk = links.Current;
        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
        {
            approvalUrl = lnk.href;
        }
    }
    if (!string.IsNullOrEmpty(approvalUrl))
    {
        Response.Redirect(approvalUrl);
    }
}
catch (Exception err)
{
    err.Log();
}
if (!pymnt.id.IsNullOrEmpty())
{
    var baseUserOrder = new BaseUserOrder() { OrderCode = pymnt.id };
    baseUserOrder.ConsumerId = baseUserOrder.CreateUser = Token.BaseUserId;
    baseUserOrder = BLL.ContainerService._BaseUserOrderService.SaveOrUpdate(baseUserOrder);
    BaseUserOrderItem baseUserOrderItem = new BaseUserOrderItem() { ArticleInfoId = id, BaseUserOrderId = baseUserOrder.Id, Nums = 1, Amount = 1 };
    BLL.ContainerService._BaseUserOrderItemService.SaveOrUpdate(baseUserOrderItem);
}
return View();
}
用户在Paypal进行了支付并支付成功,Paypal便会引导用户到我们指定的URL地址,我们在URL地址接收Paypal的订单信息,并告诉Paypal此订单入账,具体C#代码


public ActionResult OrdersChange(string paymentId, string PayerID)
{
    var baseUserOrder = BLL.ContainerService._BaseUserOrderService.GetModel(new BaseUserOrder() { OrderCode = paymentId });
    Payment pymnt = new Payment();
    if (paymentId != null)
    {
        pymnt.id = paymentId;
        pymnt = Payment.Get(PayPalAPIContext, pymnt.id);
        try
        {
            PaymentExecution pymntExecution = new PaymentExecution();
            pymntExecution.payer_id = PayerID;
            pymnt = pymnt.Execute(PayPalAPIContext, pymntExecution);
            ViewBag.Status = pymnt.state;
            baseUserOrder.Status = pymnt.state;
        }
        catch (Exception err)
        {
            err.Log();
        }
        var transaction = pymnt.transactions.FirstOrDefault();
        baseUserOrder.Amount = decimal.Parse(transaction.amount.total);
        baseUserOrder.PaymentMethod = "paypal";
        if (baseUserOrder.Name.IsNullOrEmpty()) baseUserOrder.Name = pymnt.payer.payer_info.first_name + " " + pymnt.payer.payer_info.middle_name + " " + pymnt.payer.payer_info.last_name;
        if (baseUserOrder.Email.IsNullOrEmpty()) baseUserOrder.Email = pymnt.payer.payer_info.email;
        if (baseUserOrder.Phone.IsNullOrEmpty()) baseUserOrder.Phone = pymnt.payer.payer_info.phone;
        if (baseUserOrder.Address.IsNullOrEmpty())
        {
            baseUserOrder.Address = pymnt.payer.payer_info.shipping_address.city + " " + pymnt.payer.payer_info.shipping_address.line1 + " " + pymnt.payer.payer_info.shipping_address.line2;
            if (!pymnt.payer.payer_info.shipping_address.phone.IsNullOrEmpty()) baseUserOrder.Address += " Phone:" + pymnt.payer.payer_info.shipping_address.phone;
            if (!pymnt.payer.payer_info.shipping_address.country_code.IsNullOrEmpty()) baseUserOrder.Address += " country_code:" + pymnt.payer.payer_info.shipping_address.country_code;
        }
        var authorization = transaction.related_resources.FirstOrDefault().authorization;
        if (authorization != null && !authorization.id.IsNullOrEmpty())
        {
            try
            {
                var capture = new Capture() { is_final_capture = true };
                capture.amount = new Amount() { total = transaction.amount.total, currency = transaction.amount.currency };
                authorization.Capture(PayPalAPIContext, capture);
            }
            catch (Exception err)
            {
                err.Log();
            }
        }
    }
    if (baseUserOrder != null)
    {

        baseUserOrder.ReferencesPaidCode = PayerID;
        baseUserOrder.PaymentDate = DateTime.Now;
        var cartInfos = BLL.ContainerService._BaseUserOrderItemService.CartInfos(Token.BaseUser, baseUserOrder.Id);
        baseUserOrder.Nums = cartInfos.item_count;
        BLL.ContainerService._BaseUserOrderService.SaveOrUpdate(baseUserOrder);
        for (var i = 0; i < cartInfos.BaseUserOrderItems.Count; i++)
        {
            cartInfos.BaseUserOrderItems[i].BaseUserOrderId = baseUserOrder.Id;
            cartInfos.BaseUserOrderItems[i].UpdateTime = DateTime.Now;
            var articleInfo = ContainerService._ArticleInfoService.GetModel(new ArticleInfo { Id = cartInfos.BaseUserOrderItems[i].ArticleInfoId });
            cartInfos.BaseUserOrderItems[i].Amount = (articleInfo.DownPrice ?? 0) * cartInfos.BaseUserOrderItems[i].Nums;
            cartInfos.BaseUserOrderItems[i].Status = baseUserOrder.Status;
        }
        BLL.ContainerService._BaseUserOrderItemService.Updates(cartInfos.BaseUserOrderItems);
    }
    Response.Redirect("/orderdetail.html?id=" + baseUserOrder.Id);
    return View();
}


我当初在做的时候,缺少调用Paypal的用户授权的订单入账步骤,所以账户金额就没有变动,大家做的时候不要忘记了哦!