[英]Integrating Paypal Rest API SDK to laravel 5.2
我是第一次在laravel 5.2中集成貝寶。 我正在使用PayPal SDK作為api,但是我陷入了困境。 提交付款表格時,出現以下錯誤。
“ PayPalHttpConnection.php行176中的PayPalConnectionException:訪問https://api.sandbox.paypal.com/v1/payments/payment時,出現了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');
}
}
我認為問題是重新支付到貝寶(Paypal)網站時出現的,但我無法弄清楚到底出了什么問題。
我也遇到了這個問題-就我而言,我實際上是向falpal發送了虛假數據。
第一步,嘗試捕獲異常並獲取實際的錯誤消息
// 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');
}
}
結果消息將為您提供足夠的信息來解決您的問題。
在下面,我將使用Paypal REST API粘貼適用於我的代碼。 您將需要3條路線
您還需要添加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']);
}
我希望我得到了一切-我不得不稍微整理一下代碼以簡化代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.