Php 将Paypal Rest API SDK集成到laravel 5.2

Php 将Paypal Rest API SDK集成到laravel 5.2,php,paypal,laravel-5.2,Php,Paypal,Laravel 5.2,我第一次在laravel 5.2中集成paypal。我正在使用PayPal SDK作为api,但我已经到了一个无法摆脱的地步。当我提交付款单时,我得到以下错误 “PayPalHttpConnection.php第176行中的PayPalConnectionException: 访问时获取Http响应代码400。“ 我从中获得了教程,这是我的控制器的代码 <?php namespace App\Http\Controllers; use Illuminate\Http\Request; u

我第一次在laravel 5.2中集成paypal。我正在使用PayPal SDK作为api,但我已经到了一个无法摆脱的地步。当我提交付款单时,我得到以下错误

“PayPalHttpConnection.php第176行中的PayPalConnectionException: 访问时获取Http响应代码400。“

我从中获得了教程,这是我的控制器的代码

<?php
namespace App\Http\Controllers; 
use Illuminate\Http\Request;
use App\Http\Requests;
use PayPal\Rest\ApiContext; 
use PayPal\Auth\OAuthTokenCredential;
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\ExecutePayment;
use PayPal\Api\PaymentExecution;
use PayPal\Api\Transaction;
use Session;
use Redirect;
use Config;
use URL; 
use Redirects;

class IndexController extends Controller

{

private $_api_context;

public function __construct()
{

    // setup PayPal api context
    $paypal_conf = Config::get('paypal');
    $this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));
    $this->_api_context->setConfig($paypal_conf['settings']);
}

public function paypalform()
{
   return view('sponsors.paypalform'); 
}



public function postPayment()
{
    $input = \Request::all();
    $product = $input['product'];
    $price = $input['price'];
    $shipping = 2;

    $total = $price + $shipping;



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

    $item_1 = new Item();
    $item_1->setName($product) // item name
        ->setCurrency('USD')
        ->setQuantity(2)
        ->setPrice($price); // unit price




    $item_list = new ItemList();
    $item_list->setItems([$item_1]);

    $details = new Details();
    $details->setShipping($shipping)
            ->setSubtotal($price);

    $amount = new Amount();
    $amount->setCurrency('USD')
           ->setTotal($total)
           ->setDetails($details);


     $transaction = new Transaction();
     $transaction->setAmount($amount)
         ->setItemList($item_list)
         ->setDescription('Your transaction description')
           ->setInvoiceNumber(uniqid()); // added




     $redirect_urls = new RedirectUrls();
     $redirect_urls->setReturnUrl(URL::route('payment.status'))
         ->setCancelUrl(URL::route('payment.status'));

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


     try {
    $payment->create($this->_api_context);
} catch (\PayPal\Exception\PPConnectionException $ex) {
    if (\Config::get('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;
         }
     }

     // add payment ID to session
     Session::put('paypal_payment_id', $payment->getId());

     if(isset($redirect_url)) {
         // redirect to paypal
         return Redirect::away($redirect_url);
    }

    return Redirect::route('original.route')
        ->with('error', 'Unknown error occurred');
}

}

我也面临着这个问题——在我的例子中,我实际上向贝宝发送了falsy数据

在第一步中,尝试捕获异常并获取实际错误消息

// For testing purpose use the general exception (failed to catch with paypal for me)
catch (Exception $ex) {
  if (\Config::get('app.debug')) {
    echo "Exception: " . $ex->getMessage() . PHP_EOL;
    $err_data = json_decode($ex->getData(), true);
    exit;
  } else {
    die('Some error occur, sorry for inconvenient');
  }
}
由此产生的信息应该给你足够的信息来解决你的错误

下面我向您粘贴我的代码,该代码使用PayPalRESTAPI为我工作。你需要3条路线

  • /付款/创建(创建付款)
  • /付款/成功(验证付款是否成功并从paypal重定向)
  • /付款/取消(处理paypal的取消)
您还需要添加paypal配置并在控制器中初始化它。如果您还没有paypal配置文件,您可以直接在函数中设置客户端id和密码。设置应该是这样的

 'settings' => array(
    /**
     * Available option 'sandbox' or 'live'
     */
    'mode' => 'sandbox',

    /**
     * Specify the max request time in seconds
     */
    'http.ConnectionTimeOut' => 30,

    /**
     * Whether want to log to a file
     */
    'log.LogEnabled' => true,

    /**
     * Specify the file that want to write on
     */
    'log.FileName' => storage_path() . '/logs/paypal.log',

    /**
     * Available option 'FINE', 'INFO', 'WARN' or 'ERROR'
     *
     * Logging is most verbose in the 'FINE' level and decreases as you
     * proceed towards ERROR
     */
    'log.LogLevel' => 'FINE'
)
控制器的构造函数

    $paypal_conf = config('paypal');
    $this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));
    $this->_api_context->setConfig($paypal_conf['settings']);
创建路线

    // create a payment
    public function create(Request $request)
    {
        $payer = new Payer();
        $payer->setPaymentMethod('paypal');

        $price = '10.00'; // 10 € for example

        if($price == 0) { // ensure a price above 0
            return Redirect::to('/');
        }

        // Set Item
        $item_1 = new Item();
        $item_1->setName('My Item')
            ->setCurrency('EUR')
            ->setQuantity(1)
            ->setPrice($price);

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

        $amount = new Amount();
        $amount->setCurrency('EUR')
            ->setTotal($price); // price of all items together

        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setItemList($item_list)
            ->setDescription('Fitondo Fitnessplan');

        $redirect_urls = new RedirectUrls();
        $redirect_urls->setReturnUrl(URL::to('/payment/status'))
            ->setCancelUrl(URL::to('/payments/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('Error.');
            }
        }

        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) */

        if(isset($redirect_url)) {
            // redirect to paypal
            return Redirect::away($redirect_url);
        }

        die('Error.');
    }
成功途径

public function get(Request $request)
{
    // Get the payment ID before session clear
    $payment_id = $request->paymentId;

    if (empty($request->PayerID) || empty($request->token)) {
       die('error');
    }

    $payment = Payment::get($payment_id, $this->_api_context);

    // PaymentExecution object includes information necessary 
    // to execute a PayPal account payment. 
    // The payer_id is added to the request query parameters
    // when the user is redirected from paypal back to your site
    $execution = new PaymentExecution();
    $execution->setPayerId($request->PayerID);

    //Execute the payment
    $result = $payment->execute($execution, $this->_api_context);

    if ($result->getState() == 'approved') { // payment made

        /* here you should update your db that the payment was succesful */

        return Redirect::to('/this-is-what-you-bought')
            ->with(['success' => 'Payment success']);
    }

    return Redirect::to('/')
        ->with(['error' => 'Payment failed']);
}

我希望我得到了一切——我必须稍微整理一下我的代码以简化它。

我也遇到了这个问题——在我的情况下,我实际上向paypal发送了虚假数据

在第一步中,尝试捕获异常并获取实际错误消息

// For testing purpose use the general exception (failed to catch with paypal for me)
catch (Exception $ex) {
  if (\Config::get('app.debug')) {
    echo "Exception: " . $ex->getMessage() . PHP_EOL;
    $err_data = json_decode($ex->getData(), true);
    exit;
  } else {
    die('Some error occur, sorry for inconvenient');
  }
}
由此产生的信息应该给你足够的信息来解决你的错误

下面我向您粘贴我的代码,该代码使用PayPalRESTAPI为我工作。你需要3条路线

  • /付款/创建(创建付款)
  • /付款/成功(验证付款是否成功并从paypal重定向)
  • /付款/取消(处理paypal的取消)
您还需要添加paypal配置并在控制器中初始化它。如果您还没有paypal配置文件,您可以直接在函数中设置客户端id和密码。设置应该是这样的

 'settings' => array(
    /**
     * Available option 'sandbox' or 'live'
     */
    'mode' => 'sandbox',

    /**
     * Specify the max request time in seconds
     */
    'http.ConnectionTimeOut' => 30,

    /**
     * Whether want to log to a file
     */
    'log.LogEnabled' => true,

    /**
     * Specify the file that want to write on
     */
    'log.FileName' => storage_path() . '/logs/paypal.log',

    /**
     * Available option 'FINE', 'INFO', 'WARN' or 'ERROR'
     *
     * Logging is most verbose in the 'FINE' level and decreases as you
     * proceed towards ERROR
     */
    'log.LogLevel' => 'FINE'
)
控制器的构造函数

    $paypal_conf = config('paypal');
    $this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));
    $this->_api_context->setConfig($paypal_conf['settings']);
创建路线

    // create a payment
    public function create(Request $request)
    {
        $payer = new Payer();
        $payer->setPaymentMethod('paypal');

        $price = '10.00'; // 10 € for example

        if($price == 0) { // ensure a price above 0
            return Redirect::to('/');
        }

        // Set Item
        $item_1 = new Item();
        $item_1->setName('My Item')
            ->setCurrency('EUR')
            ->setQuantity(1)
            ->setPrice($price);

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

        $amount = new Amount();
        $amount->setCurrency('EUR')
            ->setTotal($price); // price of all items together

        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setItemList($item_list)
            ->setDescription('Fitondo Fitnessplan');

        $redirect_urls = new RedirectUrls();
        $redirect_urls->setReturnUrl(URL::to('/payment/status'))
            ->setCancelUrl(URL::to('/payments/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('Error.');
            }
        }

        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) */

        if(isset($redirect_url)) {
            // redirect to paypal
            return Redirect::away($redirect_url);
        }

        die('Error.');
    }
成功途径

public function get(Request $request)
{
    // Get the payment ID before session clear
    $payment_id = $request->paymentId;

    if (empty($request->PayerID) || empty($request->token)) {
       die('error');
    }

    $payment = Payment::get($payment_id, $this->_api_context);

    // PaymentExecution object includes information necessary 
    // to execute a PayPal account payment. 
    // The payer_id is added to the request query parameters
    // when the user is redirected from paypal back to your site
    $execution = new PaymentExecution();
    $execution->setPayerId($request->PayerID);

    //Execute the payment
    $result = $payment->execute($execution, $this->_api_context);

    if ($result->getState() == 'approved') { // payment made

        /* here you should update your db that the payment was succesful */

        return Redirect::to('/this-is-what-you-bought')
            ->with(['success' => 'Payment success']);
    }

    return Redirect::to('/')
        ->with(['error' => 'Payment failed']);
}

我希望我得到了一切——我必须稍微整理一下代码以简化它。

试试
dd($payment->getId())
before
Session::put('paypal\u payment\u id',$payment->getId())并查看其响应。第二件事是确保您向paypal提供所有数据,否则它将引发相同的异常。嗨,穆罕默德,谢谢您的回复。我得到了与“PayPalHttpConnection.php第176行中的PayPalConnectionException:访问时获得Http响应代码400”相同的错误。如何检查我是否向paypal提供了所有数据。请查看您的
/logs/paypal.log
您可以在
$paypal\u conf['settings']
中找到的路径。这将有助于找出您在本地或在线资源上测试时到底遗漏了什么?请尝试
dd($payment->getId())
before
Session::put('paypal\u payment\u id',$payment->getId())并查看其响应。第二件事是确保您向paypal提供所有数据,否则它将引发相同的异常。嗨,穆罕默德,谢谢您的回复。我得到了与“PayPalHttpConnection.php第176行中的PayPalConnectionException:访问时获得Http响应代码400”相同的错误。如何检查我是否向paypal提供了所有数据。请查看您的
/logs/paypal.log
您可以在
$paypal\u conf['settings']
中找到的路径。这将有助于找出您在本地或在线来源上测试的具体缺失?