简体   繁体   English

将Paypal Rest API SDK集成到laravel 5.2

[英]Integrating Paypal Rest API SDK to laravel 5.2

I am integrating paypal for the first time in laravel 5.2. 我是第一次在laravel 5.2中集成贝宝。 I am using the PayPal SDK as the api but I have reached a point where I am stuck. 我正在使用PayPal SDK作为api,但是我陷入了困境。 when I submit a payment form I get the following error. 提交付款表格时,出现以下错误。

"PayPalConnectionException in PayPalHttpConnection.php line 176: Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payment ." “ PayPalHttpConnection.php行176中的PayPalConnectionException:访问https://api.sandbox.paypal.com/v1/payments/payment时,出现了Http响应代码400。”

I got the tutorial from this website and here is the code from my controller 我从该网站获得了教程, 是我的控制器的代码

<?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');
}

}

I think the problems comes when redireciting to paypal website but I can't figure out what exactly is going wrong. 我认为问题是重新支付到贝宝(Paypal)网站时出现的,但我无法弄清楚到底出了什么问题。

I also faced this problem - in my case it I actually sent falsy data to paypal. 我也遇到了这个问题-就我而言,我实际上是向falpal发送了虚假数据。

In a first step try to catch the Exception and get the actualy errormessage 第一步,尝试捕获异常并获取实际的错误消息

// 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');
  }
}

The resulting message should give you enough information to solve what you got wrong. 结果消息将为您提供足够的信息来解决您的问题。

Below i paste you my code which is working for me using paypal REST api. 在下面,我将使用Paypal REST API粘贴适用于我的代码。 You will need 3 routes 您将需要3条路线

  • /payments/create (create payment) / payments / create(创建付款)
  • /payments/success (validate payment was successful & redirect from paypal) /付款/成功(验证付款成功并从Paypal重定向)
  • /payments/cancel (handle cancellation of paypal) /付款/取消(取消Paypal处理)

You will also need to add you paypal config and initialize it in your controller. 您还需要添加paypal配置并在控制器中对其进行初始化。 If you do not have a paypal config file yet you can set the client id and secret directly in the function. 如果您还没有贝宝配置文件,则可以直接在函数中设置客户端ID和密码。 The settings should be like this 设置应该像这样

 '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'
)

Constructor of Controller 控制器的构造函数

    $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 Route 建立路线

    // 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.');
    }

Success Route 成功路线

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']);
}

I hope I got everything - I had to clean up my code a little to simplify it. 我希望我得到了一切-我不得不稍微整理一下代码以简化代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM