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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了访问https://api.sandbox.paypal.com时获得Http响应代码400相关的知识,希望对你有一定的参考价值。

我正在使用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 (PayPalExceptionPayPalConnectionException $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';

我怎么解决这个问题?

答案

在paypal上发生此类问题可能有两个主要原因请查看以下内容: -

1)检查您的小计,税,​​运输,如果是单项和多项,其总和应等于总数,即总计+税+运费=总计

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

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

use PayPalApiAmount;
use PayPalApiDetails;
use PayPalApiItem;
use PayPalApiItemList;
use PayPalApiPayer;
use PayPalApiPayment;
use PayPalApiRedirectUrls;
use PayPalApiTransaction;
use PayPalRestApiContext;
use PayPalAuthOAuthTokenCredential;
// 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 PayPalRestApiContext(
          new PayPalAuthOAuthTokenCredential(
            '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:\ 拒绝访问

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