访问 https://api.sandbox.paypal.com 时得到 Http 响应码 400

Posted

技术标签:

【中文标题】访问 https://api.sandbox.paypal.com 时得到 Http 响应码 400【英文标题】:Got Http response code 400 when accessing https://api.sandbox.paypal.com 【发布时间】:2017-07-26 14:00:42 【问题描述】:

我正在使用 Paypal-SDK 沙​​箱开发 Laravel 5.2

我在通话期间收到此错误,主要是 paypal 类

异常:访问https://api.sandbox.paypal.com/v1/payments/payment 时得到 Http 响应代码 400。

这是我的代码:

$payer = new Payer();
    $payer->setPaymentMethod('paypal');

    $inputs = (object) $request->all();
    $items = [];

    for ($i = 1; $i <= $request->input('items_number'); $i++) 
     
        $item_name = $request->input("item_name_$i");
        $item_quantity = $request->input("item_quantity_$i");
        $item_price = $request->input("item_price_$i");

        if(empty($item_price) || $item_price == 0)
            return redirect('/');
        

        $item = new Item();
        $item->setName($item_name)
             ->setQuantity($item_quantity)
             ->setPrice($item_price)
             ->setCurrency('USD');

        $items[] = $item;
    

    // add item to list
    $item_list = new ItemList();
    $item_list->setItems($items);


    // price of all items together
    $amount = new Amount();
    $amount->setCurrency('USD')
           ->setTotal($request->input('total_price'));

    // transaction
    $transaction = new Transaction();
    $transaction->setAmount($amount)
                ->setItemList($item_list)
                ->setDescription('This is just a demo transaction.');

    $redirect_urls = new RedirectUrls();
    $redirect_urls->setReturnUrl(URL::to('/paypal-payment/done'))
                  ->setCancelUrl(URL::to('/paypal-payment/cancel'));

    $payment = new Payment();
    $payment->setIntent('sale')
            ->setPayer($payer)
            ->setRedirectUrls($redirect_urls)
            ->setTransactions(array($transaction));

    try 
        $payment->create($this->_api_context);
     catch (\PayPal\Exception\PayPalConnectionException $ex) 
        if (config('app.debug')) 
            echo "Exception: " . $ex->getMessage() . php_EOL;
            $err_data = json_decode($ex->getData(), true);
            exit;
         else 
            die('Some error occur, Sorry for inconvenient');
        
    

    foreach($payment->getLinks() as $link) 
    
        if($link->getRel() == 'approval_url') 
            $redirect_url = $link->getHref();
            break;
        
    

    /* here you could already add a database entry that a person started buying stuff (not finished of course) */
    Session::put('paypal_payment_id', $payment->getId());

    if(isset($redirect_url)) 
        // redirect to paypal
        return redirect()->away($redirect_url);
    

    return 'This is some error';

我该如何解决这个问题?

【问题讨论】:

您必须在$err_data 变量上获得有关错误的更多信息。 嗯...谢谢你 【参考方案1】:

paypal 出现此类问题可能有两个主要原因,请查看以下内容:-

1) 检查您的小计、税金、运费(单件和多件),其总和应等于总计,即小计 + 税 + 运费 = 总计

2)检查你的returnUrl和cancelUrl应该没有空格和特殊字符使用urlencode。

下面的代码对我有用,它可以帮助你我也为此浪费了很多时间:-

use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
// use these at the top of the class 


/**
     * Function     : paypalPay()
     * Description  : Used to pay the payment using paypal
     * Author       : kantsverma
     * Parameters   :
     */
    public function paypalPay()
           
        require_once(ROOT . DS . 'vendor' . DS . "autoload.php");       

        // integrate paypal 
        $apiContext = new \PayPal\Rest\ApiContext(
          new \PayPal\Auth\OAuthTokenCredential(
            'YOUR APPLICATION CLIENT ID',
            'YOUR APPLICATION CLIENT SECRET'
            )
        );

        $payer = new Payer();
        $payer->setPaymentMethod("paypal");
        //Itemized information (Optional) Lets you specify item wise information

        $item1 = new Item();
        $item1->setName('Ground Coffee 40 oz')
            ->setCurrency('USD')
            ->setQuantity(1)
            ->setPrice(17);

        $itemList = new ItemList();
        $itemList->setItems(array($item1));

        $details = new Details();
        $details->setShipping(1)
            ->setTax(2)
            ->setSubtotal(17);

        $amount = new Amount();
        $amount->setCurrency("USD")
            ->setTotal(20)
            ->setDetails($details);

        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setItemList($itemList)
            ->setDescription("Payment description")
            ->setInvoiceNumber(uniqid());

        $baseUrl = $this->getBaseUrl();

        $redirectUrls = new RedirectUrls();
        $redirectUrls->setReturnUrl("$baseUrl")
            ->setCancelUrl("$baseUrl");

        $payment = new Payment();


        $payment->setIntent("order")
            ->setPayer($payer)
            ->setRedirectUrls($redirectUrls)
            ->setTransactions(array($transaction));
        //For Sample Purposes Only.

        $request = clone $payment;

        try 
            $paymentdetail = $payment->create($apiContext);
            echo '<pre>';
            print_r($paymentdetail);
            echo '</pre>';

            die('inside try ');
         catch (Exception $ex) 
            //NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY

            ResultPrinter::printError("Created Payment Order Using PayPal. Please visit the URL to Approve.", "Payment", null, $request, $ex);
            die('Inside catch');
        
        //Get redirect url
        //The API response provides the url that you must redirect the buyer to. Retrieve the url from the $payment->getApprovalLink() method

        $approvalUrl = $payment->getApprovalLink();
        //NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY

         ResultPrinter::printResult("Created Payment Order Using PayPal. Please visit the URL to Approve.", "Payment", "<a href='$approvalUrl' >$approvalUrl</a>", $request, $payment);

        return $payment;    
    

我已经创建了上面的函数并调用了你可以删除 die 和 print_r() 在 try 它对我有用的函数。

【讨论】:

以上是关于访问 https://api.sandbox.paypal.com 时得到 Http 响应码 400的主要内容,如果未能解决你的问题,请参考以下文章

如何设置MSSQL数据库访问用户及访问权限

在SQL数据访问中如何对不同级别设置访问权限

有效访问时间和平均访问时间

一个网站用域名可以访问,用ip不能访问,是为啥?

C盘 位置不可用,无法访问C:\ 拒绝访问

文件拒绝访问无法访问怎么办