沙盒测试第二次支付失败 Paypal 集成 asp.net mvc

Posted

技术标签:

【中文标题】沙盒测试第二次支付失败 Paypal 集成 asp.net mvc【英文标题】:Sandbox test second Payment Failed Paypal Integration asp.net mvc 【发布时间】:2018-12-10 00:16:40 【问题描述】:

我正在尝试将 Paypal 集成到我的 .net mvc 项目中。我创建了一个应用程序并在 web.config 和我的控制器中添加了一个代码(要查看代码,请参见下文)。 我可以在新帐户上进行单笔交易,但是当我调用另一个交易时,它返回 Transaction failed:远程服务器返回错误:(400) Bad Request。

下面是我的 web.config 代码

    <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <section name="paypal" type="PayPal.SDKConfigHandler, PayPal" />
  </configSections>
  <!-- PayPal SDK settings -->
  <paypal>
    <settings>
      <add name="mode" value="sandbox" />
      <!--<add name="clientId" value="AfLQXEBebCzqXtXyPYW987x5Zg75PXpTgYACmv8i9pMaWiMCN0U-FIkKPngd3WQ4YK9J-_gE1ZfMiQlb" />
      <add name="clientSecret" value="EFNJZjqrmGkAY-W4-NmCRq-DgkEmCgRteDY_v4aBf6TTU55ZwARMj0399UfFZ5T7iExAtoqq3tdOuyd" />-->
      <add name="clientId" value="AQ3-ATuhAujxd7-Y5BVOKw8fdlIt5KlDul1d0OIJ4hQavS0smxF0Np_MfO6tZXAcuYqklG33yycQnNvj" />
      <add name="clientSecret" value="EA77LpQNkL8U6xH96A2VZTKXjdthToF8yFsw4SKRfGmY5iHMxTv_yxJXMxBHCeXVnNFF_EO5UOeDjq1Q" />
    </settings>
  </paypal>

以下是我调用paypal api的控制器

public ActionResult PaymentWithPaypal(string Cancel = null)
    
        //getting the apiContext  
        APIContext apiContext = PaypalConfiguration.GetAPIContext();
        ////try
        ////
            //A resource representing a Payer that funds a payment Payment Method as paypal  
            //Payer Id will be returned when payment proceeds or click to pay  
            string payerId = Request.Params["PayerID"];
            if (string.IsNullOrEmpty(payerId))
            
                //this section will be executed first because PayerID doesn't exist  
                //it is returned by the create function call of the payment class  
                // Creating a payment  
                // baseURL is the url on which paypal sendsback the data.  
                string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Home/PaymentWithPayPal?";
                //here we are generating guid for storing the paymentID received in session  
                //which will be used in the payment execution  
                var guid = Convert.ToString((new Random()).Next(100000));
                //CreatePayment function gives us the payment approval url  
                //on which payer is redirected for paypal account payment  
                var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid);
                //get links returned from paypal in response to Create function call  
                var links = createdPayment.links.GetEnumerator();
                string paypalRedirectUrl = null;
                while (links.MoveNext())
                
                    Links lnk = links.Current;
                    if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                    
                        //saving the payapalredirect URL to which user will be redirected for payment  
                        paypalRedirectUrl = lnk.href;
                    
                
                // saving the paymentID in the key guid  
                Session.Add(guid, createdPayment.id);
                return Redirect(paypalRedirectUrl);
            
            else
            
                // This function exectues after receving all parameters for the payment  
                var guid = Request.Params["guid"];
                var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
                //If executed payment failed then we will show payment failure message to user  
                if (executedPayment.state.ToLower() != "approved")
                
                    return View("FailureView");
                
            
        //
        catch (Exception ex)
        
            return View("FailureView");
        
        //on successful payment, show success page to user.  
        return View("SuccessView");
    

    private Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId)
    
        var paymentExecution = new PaymentExecution()
        
            payer_id = payerId
        ;
        this.payment = new Payment()
        
            id = paymentId
        ;
        var a = payment.Execute(apiContext, paymentExecution);
        return a;
    
    private Payment CreatePayment(APIContext apiContext, string redirectUrl)
    
        //create itemlist and add item objects to it  
        var itemList = new ItemList()
        
            items = new List<Item>()
        ;
        //Adding Item Details like name, currency, price etc  
        itemList.items.Add(new Item()
        
            name = "Item Name comes here",
            currency = "USD",
            price = "10",
            quantity = "1",
            sku = "sku"
        );
        var payer = new Payer()
        
            payment_method = "paypal"
        ;
        // Configure Redirect Urls here with RedirectUrls object  
        var redirUrls = new RedirectUrls()
        
            cancel_url = redirectUrl + "&Cancel=true",
            return_url = redirectUrl
        ;
        // Adding Tax, shipping and Subtotal details  
        var details = new Details()
        
            tax = "1",
            shipping = "1",
            subtotal = "10"
        ;
        //Final amount with details  
        var amount = new Amount()
        
            currency = "USD",
            total = "12", // Total must be equal to sum of tax, shipping and subtotal.  
            details = details
        ;
        var transactionList = new List<Transaction>();
        // Adding description about the transaction  
        transactionList.Add(new Transaction()
        
            description = "Transaction description",
            invoice_number = "your generated invoice number", //Generate an Invoice No  
            amount = amount,
            item_list = itemList
        );
        this.payment = new Payment()
        
            intent = "sale",
            payer = payer,
            transactions = transactionList,
            redirect_urls = redirUrls
        ;
        // Create a payment using a APIContext  
        return this.payment.Create(apiContext);
    

【问题讨论】:

希望你改一下paypalclientSecret,以后不要再发这种保密信息了)。哦,是沙盒……另外我看到两个按键相同的clientSecret部分,看起来很奇怪。 我建议您在调试时单步执行您的代码。它会告诉您代码失败的原因/位置。这里没有人会为你做这件事。希望如果您知道什么/在哪里,您可以弄清楚该做什么,否则,请返回并根据您调试的具体内容修改您的问题。就目前而言,它“过于宽泛”。 Hth. 【参考方案1】:

使用下面的代码来解决问题。

public Payment CreatePayment(APIContext apiContext, string redirectUrl)

    //create itemlist and add item objects to it
    var itemList = new ItemList()  items = new List<Item>() ;

    //Adding Item Details like name, currency, price etc
    itemList.items.Add(new Item()
    
        name = "Item Name comes here",
        currency = "USD",
        price = "4",
        quantity = "1",
        sku = "sku"
    );

    var payer = new Payer()  payment_method = "paypal" ;

    // Configure Redirect Urls here with RedirectUrls object
    var redirUrls = new RedirectUrls()
    
        cancel_url = redirectUrl + "&Cancel=true",
        return_url = redirectUrl
    ;

    // Adding Tax, shipping and Subtotal details
    var details = new Details()
    
        tax = "1",
        shipping = "1",
        subtotal = "4",
        shipping_discount = "-1"
    ;

    //Final amount with details
    var amount = new Amount()
    
        currency = "USD",
        total = "5", // Total must be equal to sum of tax, shipping and subtotal.
        details = details
    ;

    var transactionList = new List<Transaction>();
    // Adding description about the transaction
    transactionList.Add(new Transaction()
    
        description = "Transaction description",
        invoice_number = Convert.ToString((new Random()).Next(100000)), 
        amount = amount,
        item_list = itemList
    );


    this.payment = new Payment()
    
        intent = "sale",
        payer = payer,
        transactions = transactionList,
        redirect_urls = redirUrls
    ;

    // Create a payment using a APIContext
    return this.payment.Create(apiContext);

问候 奥姆卡尔。

【讨论】:

以上是关于沙盒测试第二次支付失败 Paypal 集成 asp.net mvc的主要内容,如果未能解决你的问题,请参考以下文章

沙盒测试模式下 Android 中的 Paypal 支付网关集成问题

支付失败“商户不接受此类支付”

Paypal 沙盒 - 测试支付

使用 PayPal-PHP-SDK 进行第三方支付的 Paypal 沙盒测试

贝宝沙盒账户交易失败

贝宝沙盒测试错误