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

问题描述 投票:0回答:1

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

我怎么解决这个问题?

php laravel paypal
1个回答
0
投票

在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中它对我有效。

© www.soinside.com 2019 - 2024. All rights reserved.