laravel - PayPal - 访问 https://api.sandbox.paypal.com/v1/payments/payment/PAYID-L6ZZRNY2CA2198940171953X/execute 时获得 Http 响应代码 400
问题描述
我正在使用我在另一个平台上使用的相同代码,但不同之处在于我在这里使用欧元。我创建了一个不同的 PayPal 帐户,也是欧元。
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 postPayment()
{
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$items = array();
$subtotal = 0;
$cart = \Session::get('cart');
$currency = 'EUR';
//PEDIDO ACTUAL
$pedidoActual = DB::table('pedido as pe')
->select('pe.subtotal')
->where('pe.idpedido','=',$cart['idpedido'])
->first();
$monto = number_format($pedidoActual->subtotal,2);
$item = new Item();
$item->setName("Pedido de Momento Mágico")
->setCurrency($currency)
->setDescription("Entrega a domicilio incluido")
->setQuantity(1)
->setPrice($monto);
$items[] = $item;
$subtotal = $monto;
///////////////
$item_list = new ItemList();
$item_list->setItems($items);
//Nos sirve si queremos agregar un costo por el envío
$details = new Details();
$subtotal = $subtotal;
$details->setSubtotal($subtotal)
->setShipping(0);
//Es el objeto que tiene la moneda, el detalle a pagar y envio
$amount = new Amount();
$amount->setCurrency($currency)
->setTotal($subtotal)
->setDetails($details);
//Los datos de la transacción
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($item_list)
->setDescription('Pedido de Prueba en App Store');
//Recibe la ruta si se realiza o se cancela el pago
$redirect_urls = new RedirectUrls();
$redirect_urls->setReturnUrl(\URL::route('payment.status'))
->setCancelUrl(\URL::route('payment.status'));
//A traves del objeto Payment creamos el pago
$payment = new Payment();
$payment->setIntent('Sale') //De tipo Venta directa, puede ser de otros tipos
->setPayer($payer)
->setRedirectUrls($redirect_urls)
->setTransactions(array($transaction));
//Enviamos el pago y si hay errores lo mostramos en el Debug
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('Ups! Algo salió mal');
}
}
// Si todo salió bien, Paypal nos devuelve información
foreach($payment->getLinks() as $link) {
if($link->getRel() == 'approval_url') {
$redirect_url = $link->getHref();
break;
}
}
// add payment ID to session // para darle seguimiento al usuario que lo hizo
\Session::put('paypal_payment_id', $payment->getId());
if(isset($redirect_url)) {
// redirect to paypal
return \Redirect::away($redirect_url);
}
return \Redirect::route('home')
->with('error', 'Ups! Error desconocido.');
}
public function getPaymentStatus(Request $request)
{
// Get the payment ID before session clear
$payment_id = \Session::get('paypal_payment_id');
$cart = \Session::get('cart');
// clear the session payment ID
\Session::forget('paypal_payment_id');
$input = $request->all();
$payerId = Arr::except($input,array('PayerID'));
$token = Arr::except($input,array('token'));
//$payerId = \Input::get('PayerID');
//$token = \Input::get('token');
//if (empty(\Input::get('PayerID')) || empty(\Input::get('token'))) {
if (empty($payerId) || empty($token) || empty($payment_id)) {
$notificarError = (new MailController)->errorPagoPaypal();
return \Redirect::route('home')
->with('message', 'Hubo un problema al intentar pagar con Paypal');
}
//Si se pudo realizar el pago
$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($payerId);
//Execute the payment
$result = $payment->execute($execution, $this->_api_context);
//echo '<pre>';print_r($result);echo '</pre>';exit; // DEBUG RESULT, remove it later
if ($result->getState() == 'approved') { // payment made
// Eliminar carrito
// Enviar correo a user
$fecha_prog_envio = (new CartController)->obtenerFechaEnvio($cart['tipo_producto']);
// Enviar correo a user
$notificarPagoPayPal = (new MailController)->notificarPagoIngresado($fecha_prog_envio,'PayPal');
$this->saveOrder(\Session::get('cart'),$fecha_prog_envio);
\Session::forget('cart');
return \Redirect::route('home')
->with('message', 'Pago realizado correctamente.');
}
return \Redirect::route('home')
->with('message', 'La compra fue cancelada');
}
我已经阅读了所有论坛,检查了金额是否正确,但它不起作用。这不是身份验证问题,因为我尝试连接到其他平台并且错误是相同的。
我想错误可能来自货币兑换,总金额。但我没有发现错误。
解决方案
$execution->setPayerId($payerId);
$payerId
在这个阶段使用它有什么价值?记录下来。
它应该是一个纯字符串值,但在此之前设置和检查 payerId 的代码看起来很有趣,我不相信这个值。
推荐阅读
- redis - 多个微服务和 Redis - 云中每个应用程序一个数据库与一个节点
- visual-studio-2010 - Microsoft Visual Studio 无法启动程序程序集 x86
- css - 使用图像内容缩放和对齐简单的网站
- google-sheets - 谷歌表格功能试图重命名工作表
- javascript - 如何将文本放在随机数之前
?
- java - spring batch using spring boot:从配置或命令行读取参数并在作业中使用它们
- node.js - 将 Firebase CLI 更新到 8.4.0 时会出现关于“不支持的引擎”的错误,说 '{"node":">=10"}'
- xamarin - Xamarin Forms:当文本和显示设置为大时,其他所有内容也是如此
- c++ - 使用 cout 语句和 connect() 会导致我的程序崩溃的原因是什么
- java - Java:如何解析文件以获取生成图的边