我在laravel 5.2中第一次整合了paypal。我使用PayPal SDK作为api,但我已经到了我被卡住的地步。当我提交付款表格时,我收到以下错误。
PayPalHttpConnection.php第176行中的" PayPalConnectionException: 访问https://api.sandbox.paypal.com/v1/payments/payment时获得了Http响应代码400。"
我从this website获得了教程,这是我控制器的代码
<?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网站时会遇到问题,但我无法弄清楚到底出了什么问题。
答案 0 :(得分:2)
我也遇到过这个问题 - 在我的情况下,我实际上是向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');
}
}
结果消息应该为您提供足够的信息来解决您的错误。
下面我粘贴你使用paypal REST api为我工作的代码。你需要3条路线
您还需要添加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'
)
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 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']);
}
我希望我得到了所有东西 - 我必须稍微清理我的代码以简化它。