执行付款 - PayPal REST API

时间:2016-12-29 13:17:48

标签: php paypal-rest-sdk paypal

PayPal REST ExpressCheckout API包含两部分: 验证并执行。 一切顺利,但执行失败。

我正在关注此示例代码:http://paypal.github.io/PayPal-PHP-SDK/sample/doc/payments/ExecutePayment.html

我真的不明白这个过程。它尝试获取我的URL中不存在的一些参数。我什么时候使用返回网址?

这是我的HTML:

{% extends 'layout/master.twig' %}

{% block title %} {{ parent() }}PayPal {% endblock title %}

{% block head %}
    <script src="https://www.paypalobjects.com/api/checkout.js"></script>
{% endblock %}

{% block header %} Testing PayPal {% endblock header %}


{% block content %}

    <div id="paypal-button"></div>

{% endblock content %}


{% block scripts %}
    <script>
        paypal.Button.render({

            env: 'sandbox', // Optional: specify 'production' environment

            payment: function (resolve, reject) {

                var CREATE_PAYMENT_URL = 'http://patch-request.app/paypal/payment/create';

                paypal.request.post(CREATE_PAYMENT_URL)
                    .then(function (data) {
                        resolve(data.id);
                    })
                    .catch(function (err) {
                        reject(err);
                    });
            },

            onAuthorize: function (data) {
                console.log(data);
                // Note: you can display a confirmation page before executing

                var EXECUTE_PAYMENT_URL = 'http://patch-request.app/paypal/payment/execute';

                paypal.request.post
                    (
                    EXECUTE_PAYMENT_URL,
                        {
                            paymentID: data.paymentID,
                            payerID: data.payerID
                        }
                    )
                    .then(function (data) {
                        /* Go to a success page */
                        console.log('SUCCESS!!!!!!!!!');
                        console.log(data);
                    })
                    .catch(function (err) {
                        /* Go to an error page  */
                        console.log('ERROR!!!!!!!!!');
                        console.log(data);
                    });
            }

        }, '#paypal-button');
    </script>
{% endblock scripts %}

以下是PHP的身份验证部分:

    /**
     * Initialize a payment that needs to be verified
     *
     * @return JSON paymentID
     */
    public function authorize_payment ()
    {
        $payer = new Payer();
        $payer->setPaymentMethod("paypal");

        $item1 = new Item();
        $item1->setName('Ground Coffee 40 oz')
            ->setCurrency('USD')
            ->setQuantity(1)
            ->setSku("123123")// Similar to `item_number` in Classic API
            ->setPrice(7.5);
        $item2 = new Item();
        $item2->setName('Granola bars')
            ->setCurrency('USD')
            ->setQuantity(5)
            ->setSku("321321")// Similar to `item_number` in Classic API
            ->setPrice(2);

        $itemList = new ItemList();
        $itemList->setItems([$item1, $item2]);

        $details = new Details();
        $details->setShipping(1.2)
            ->setTax(1.3)
            ->setSubtotal(17.50);

        $amount = new Amount();
        $amount->setCurrency("USD")
            ->setTotal(20)
            ->setDetails($details);

        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setItemList($itemList)
            ->setDescription("Payment description")
            ->setInvoiceNumber(uniqid());

//        $baseUrl = getBaseUrl();
        $baseUrl = "http://patch-request.app";
        $redirectUrls = new RedirectUrls();
        $redirectUrls->setReturnUrl("$baseUrl/blog")
            ->setCancelUrl("$baseUrl/blog/cleardb");

        $payment = new Payment();
        $payment->setIntent("sale")
            ->setPayer($payer)
            ->setRedirectUrls($redirectUrls)
            ->setTransactions([$transaction]);

        $request = clone $payment;

        try
        {
            $payment->create($this->apiContext); //$payment is a JSON
        }
        catch (Exception $ex)
        {
            echo 'Sth went wrong';
        }

        $approvalUrl = $payment->getApprovalLink();
//        d($approvalUrl);

//        ResultPrinter::printResult("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment",
//            "<a href='$approvalUrl' >$approvalUrl</a>", $request, $payment);

//        return json_encode(['paymentID' => $payment->id]);
        return $payment;
    }

这是PHP失败的执行部分:

    /**
     * Execute the authorized payment
     */
    public function execute_payment ()
    {
        ChromePhp::log('outside');
        ChromePhp::log($_GET);

//        if (isset($_GET['success']) && $_GET['success'] == 'true')
//        {
            ChromePhp::log('inside');
            $paymentId = $_GET['paymentId'];
            $payment = Payment::get($paymentId, $this->apiContext);

            $execution = new PaymentExecution();
            $execution->setPayerId($_GET['PayerID']);

            $transaction = new Transaction();
            $amount = new Amount();
            $details = new Details();

            $details->setShipping(2.2)
                ->setTax(1.3)
                ->setSubtotal(17.50);

            $amount->setCurrency('USD');
            $amount->setTotal(21);
            $amount->setDetails($details);
            $transaction->setAmount($amount);

            $execution->addTransaction($transaction);

            try
            {
                $result = $payment->execute($execution, $this->apiContext);
                ChromePhp::log($result);

                try
                {
                    // Could not get payment
                    $payment = Payment::get($paymentId, $this->apiContext);
                    ChromePhp::log($payment);
                }
                catch (Exception $ex)
                {
                    exit(1);
                }
            }
            catch (Exception $ex)
            {
                // Could not execute payment
                exit(1);
            }

            return $payment;
//        }
//        else
//        {
             //User cancelled the approval
//            exit;
//        }
    }

1 个答案:

答案 0 :(得分:2)

他们网站上的文档非常可怕。他们给你的示例Javascript在 POST 请求中发送这两个变量,PHP-SDK示例查找 GET 请求。他们只是要求人们遇到问题。

您可以看到以下代码段在POST请求中同时发送paymentIDpayerID

onAuthorize: function (data) {
console.log(data);
// Note: you can display a confirmation page before executing

var EXECUTE_PAYMENT_URL = 'http://patch-request.app/paypal/payment/execute';

paypal.request.post
    (
    EXECUTE_PAYMENT_URL,
        {
            paymentID: data.paymentID,  // this object is sent with the above URL
            payerID: data.payerID .     // as a payload with the POST request
        }
    )
    .then(function (data) {
        /* Go to a success page */
        console.log('SUCCESS!!!!!!!!!');
        console.log(data);
    })
    .catch(function (err) {
        /* Go to an error page  */
        console.log('ERROR!!!!!!!!!');
        console.log(data);
    });

}

尝试将PHP示例中对此的任何引用修改为$_POST,如下所示:

$paymentId = $_GET['paymentId'];

为:

$paymentId = $_POST['paymentId'];