PayPal Rest API - 使用更新的交易信息执行付款

Posted

技术标签:

【中文标题】PayPal Rest API - 使用更新的交易信息执行付款【英文标题】:PayPal Rest API - Execute Payment with updated transaction info 【发布时间】:2013-11-07 13:22:20 【问题描述】:

我正在使用 C# 和 PayPal Rest API 来获得批准的付款并执行它。但是,我需要更新与已批准付款相关的交易。 PayPal 文档内容如下:

使用此调用执行(完成)已 付款人批准。您可以选择更新交易 通过传入一个或多个执行付款时的信息 交易。

这是我的代码

//Update the payment details in case totals changed because of a new address/zipcode
Details amountDetails = new Details();
amountDetails.subtotal = ValidationHelper.GetString(prices[Order.CartPricesEnum.Subtotal], "0");
amountDetails.tax = ValidationHelper.GetString(prices[Order.CartPricesEnum.Tax], "0");
amountDetails.shipping = ValidationHelper.GetString(prices[Order.CartPricesEnum.Shipping], "0");

Amount amount = new Amount();
amount.total = ValidationHelper.GetString(prices[Order.CartPricesEnum.Total], "0");
amount.currency = "USD";
amount.details = amountDetails;

//update the transaction to make sure we have accounted for any updated prices
Transactions trn = new Transactions();
trn.amount = amount;

List<Transactions> trns = new List<Transactions>();                    
trns.Add(trn);

//Create a payment execution object
PaymentExecution paymentExecution = new PaymentExecution();
paymentExecution.payer_id = payPalPayerID;
paymentExecution.transactions = trns;                    

//Execute (complete) the payment
Payment newPayment = payment.Execute(accessToken, paymentExecution);

问题是当它运行时出现以下错误:

"name":"VALIDATION_ERROR","details":["field":"transactions[0].total","issue":"Required field missing","field":"transactions[0].currency","issue":"Required field missing","field":"transactions[0].amount","issue":"This field name is not defined for this resource type"],"message":"Invalid request - see details","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#VALIDATION_ERROR","debug_id":"bcba38f3c56d7"

这告诉我我缺少 .total 和 .currency,并且 .amount 字段未定义。但是,您可以清楚地看到我正在设置总计和货币,并且金额字段是您可以根据 PayPal API 文档在交易对象上设置的唯一字段:

transactions    
array of transaction objects    
Transactional details if updating a payment. Note that this instance of the transactions object accepts only the amount object.

所以,我的问题是:我如何才能获得批准的付款,更新付款交易的价格,然后执行该付款?

【问题讨论】:

有过这个工作吗? 实际上,PayPal Rest API 目前不支持我尝试做的事情。我不得不使用遗留框架重写所有内容。在与 PayPal 支持人员交谈后,我发现了这一点。该部分的文档不是很清楚。 谢谢,我最终选择了旧版库——还有其他限制(例如在已批准的交易中检索发货信息)。 【参考方案1】:

我不是这方面的专家,但我刚刚实施了类似的付款交易,我认为必须分两步完成:创建付款然后执行付款,因为买家必须登录到他的 PayPal 帐户并确认之间的付款。这种方式对我有用。

所以你需要的是这样的(抱歉我的代码是 VB.NET):

'Create payment
Dim createdPayment As Payment = payment.Create(apiContext)

然后在从 PayPal 回发时,您可以执行付款:

'Execute payment
Dim paymentExecution As New PaymentExecution()
Dim executedPayment As Payment = payment.Execute(apiContext, paymentExecution)

以下是从 API 提供的示例中获取的完整示例:

// #Create Payment Using PayPal Sample
// This sample code demonstrates how you can process a 
// PayPal Account based Payment.
// API used: /v1/payments/payment
using System;
using System.Web;
using PayPal;
using PayPal.Api.Payments;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace RestApiSample

    public partial class PaymentWithPayPal : System.Web.UI.Page
    
        protected void Page_Load(object sender, EventArgs e)
        
            HttpContext CurrContext = HttpContext.Current;
            Payment pymnt = null;

            // ### Api Context
            // Pass in a `APIContext` object to authenticate 
            // the call and to send a unique request id 
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly. 
             // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext..
            APIContext apiContext = Configuration.GetAPIContext();

            // ## ExecutePayment
            if (Request.Params["PayerID"] != null)
            
                pymnt = new Payment();
                if (Request.Params["guid"] != null)
                
                    pymnt.id = (string)Session[Request.Params["guid"]];

                
                try
                
                    PaymentExecution pymntExecution = new PaymentExecution();
                    pymntExecution.payer_id = Request.Params["PayerID"];

                    Payment executedPayment = pymnt.Execute(apiContext, pymntExecution);
                    CurrContext.Items.Add("ResponseJson", JObject.Parse(executedPayment.ConvertToJson()).ToString(Formatting.Indented));
                
                catch (PayPal.Exception.PayPalException ex)
                
                    CurrContext.Items.Add("Error", ex.Message);
                
            

            // ## Creating Payment
            else
            
                // ###Items
                // Items within a transaction.
                Item item = new Item();
                item.name = "Item Name";
                item.currency = "USD";
                item.price = "15";
                item.quantity = "5";
                item.sku = "sku";

                List<Item> itms = new List<Item>();
                itms.Add(item);
                ItemList itemList = new ItemList();
                itemList.items = itms;

                // ###Payer
                // A resource representing a Payer that funds a payment
                // Payment Method
                // as `paypal`
                Payer payr = new Payer();
                payr.payment_method = "paypal";
                Random rndm = new Random();
                var guid = Convert.ToString(rndm.Next(100000));

                string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?";

                // # Redirect URLS
                RedirectUrls redirUrls = new RedirectUrls();
                redirUrls.cancel_url = baseURI + "guid=" + guid;
                redirUrls.return_url = baseURI + "guid=" + guid;

                // ###Details
                // Let's you specify details of a payment amount.
                Details details = new Details();
                details.tax = "15";
                details.shipping = "10";
                details.subtotal = "75";

                // ###Amount
                // Let's you specify a payment amount.
                Amount amnt = new Amount();
                amnt.currency = "USD";
                // Total must be equal to sum of shipping, tax and subtotal.
                amnt.total = "100";
                amnt.details = details;

                // ###Transaction
                // A transaction defines the contract of a
                // payment - what is the payment for and who
                // is fulfilling it. 
                List<Transaction> transactionList = new List<Transaction>();
                Transaction tran = new Transaction();
                tran.description = "Transaction description.";
                tran.amount = amnt;
                tran.item_list = itemList;
                // The Payment creation API requires a list of
                // Transaction; add the created `Transaction`
                // to a List
                transactionList.Add(tran);

                // ###Payment
                // A Payment Resource; create one using
                // the above types and intent as `sale` or `authorize`
                pymnt = new Payment();
                pymnt.intent = "sale";
                pymnt.payer = payr;
                pymnt.transactions = transactionList;
                pymnt.redirect_urls = redirUrls;

                try
                
                    // Create a payment using a valid APIContext
                    Payment createdPayment = pymnt.Create(apiContext);

                    CurrContext.Items.Add("ResponseJson", JObject.Parse(createdPayment.ConvertToJson()).ToString(Formatting.Indented));

                    var links = createdPayment.links.GetEnumerator();

                    while (links.MoveNext())
                    
                        Links lnk = links.Current;
                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        
                            CurrContext.Items.Add("RedirectURL", lnk.href);
                        
                    
                    Session.Add(guid, createdPayment.id);
                
                catch (PayPal.Exception.PayPalException ex)
                
                    CurrContext.Items.Add("Error", ex.Message);
                
            
            CurrContext.Items.Add("RequestJson", JObject.Parse(pymnt.ConvertToJson()).ToString(Formatting.Indented));

            Server.Transfer("~/Response.aspx");

        
    

【讨论】:

【参考方案2】:

看起来 paymentExecution 交易对象只接受金额对象而不接受交易对象。

https://developer.paypal.com/docs/api/#execute-an-approved-paypal-payment

【讨论】:

以上是关于PayPal Rest API - 使用更新的交易信息执行付款的主要内容,如果未能解决你的问题,请参考以下文章

需要帮助使用 PayPal REST API 或 C# 中的任何其他方法获取 PayPal 交易

使用新的 REST API 应用程序从经典(IPN 端点)搜索 Paypal 交易

PayPal REST API - 已退款交易错误

PayPal Adaptive Payments REST API 还是经典?

带有 PHP SDK 的 Paypal REST API - 如何获取交易号?

Paypal 一次性购买和定期付款,通过 rest api 使用快速结帐在单笔交易中进行