首页 > 解决方案 > 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');
    }

我已经阅读了所有论坛,检查了金额是否正确,但它不起作用。这不是身份验证问题,因为我尝试连接到其他平台并且错误是相同的。

在此处输入图像描述

我想错误可能来自货币兑换,总金额。但我没有发现错误。

标签: laravelpaypal

解决方案


$execution->setPayerId($payerId);

$payerId在这个阶段使用它有什么价值?记录下来。

它应该是一个纯字符串值,但在此之前设置和检查 payerId 的代码看起来很有趣,我不相信这个值。


推荐阅读