简体   繁体   English

PHP PayPal服务器端REST API

[英]PHP PayPal Server side REST API

I'm playing about with the paypal rest API and I can't get it to work. 我正在使用Paypal Rest API,但无法正常工作。

I've copied the code they supply for the create payment. 我已经复制了他们提供的用于创建付款的代码。 When I run it and echo the response seems okay. 当我运行它并回显时,响应似乎还可以。 COde is : 编码是:

            <?php

            // 1. Autoload the SDK Package. This will include all the files and classes to your autoloader
            require __DIR__  . '/PayPal-PHP-SDK/autoload.php';
            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\Transaction;
            // 2. Provide your Secret Key. Replace the given one with your app clientId, and Secret
            // h**ps://developer.paypal.com/webapps/developer/applications/myapps
            $apiContext = new \PayPal\Rest\ApiContext(
                new \PayPal\Auth\OAuthTokenCredential(
                    'ClientID IS HERE AND IS CORRECT',     // ClientID
                    'Secret IS HERE AND IS CORRECT'      // ClientSecret
                )
            );

            // 3. Lets try to create a Payment
            // h**ps://developer.paypal.com/docs/api/payments/#payment_create
            $payer = new \PayPal\Api\Payer();
            $payer->setPaymentMethod('paypal');

            /*$amount = new \PayPal\Api\Amount();
            $amount->setTotal('1.00');
            $amount->setCurrency('USD');*/


            $item1 = new Item();
            $item1->setName('Ground Coffee 40 oz')
                ->setCurrency('USD')
                ->setQuantity(1)
                ->setPrice(7.5);

            $item2 = new Item();
            $item2->setName('Granola bars')
                ->setCurrency('USD')
                ->setQuantity(5)
                ->setPrice(2);

            $itemList = new ItemList();
            $itemList->setItems(array($item1, $item2));
            //Additional payment details

            //Use this optional field to set additional payment information such as tax, shipping charges etc.
            $details = new Details();
            $details->setShipping(1.2)
                ->setTax(1.3)
                ->setSubtotal(17.50);

            //Amount

            //Lets you specify a payment amount. You can also specify additional details such as shipping, tax.
            $amount = new Amount();
            $amount->setCurrency("USD")
                ->setTotal(20)
                ->setDetails($details);

            $transaction = new \PayPal\Api\Transaction();
            $transaction->setAmount($amount);

            $redirectUrls = new \PayPal\Api\RedirectUrls();
            $redirectUrls->setReturnUrl("h**ps://example.com/your_redirect_url.html")
                ->setCancelUrl("h**ps://example.com/your_cancel_url.html");

            $payment = new \PayPal\Api\Payment();
            $payment->setIntent('sale')
                ->setPayer($payer)
                ->setTransactions(array($transaction))
                ->setRedirectUrls($redirectUrls);

            // 4. Make a Create Call and print the values
            try {
                $payment->create($apiContext);

              //  echo "\n\nRedirect user to approval_url: " . $payment->getApprovalLink() . "\n";
            }
            catch (\PayPal\Exception\PayPalConnectionException $ex) {
                // This will print the detailed information on the exception.
                //REALLY HELPFUL FOR DEBUGGING
                echo $ex->getData();
            }
            return($payment);
            ?>

I think this works 我认为这有效

Next I created the button script using their sample code: 接下来,我使用他们的示例代码创建了按钮脚本:

            <!DOCTYPE html>

            <head>
                <meta h**p-equiv="X-UA-Compatible" content="IE=edge" />
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <script src="h**ps://www.paypalobjects.com/api/checkout.js"></script>
            </head>

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

                <script>
                    paypal.Button.render({

                        env: 'sandbox', // sandbox | production

                        commit: true,

                        payment: function() {

                            // Set up a url on your server to create the payment
                            var CREATE_URL = 'h**ps://MySite.com/PayPalRest/first.php';

                            // Make a call to your server to set up the payment
                            console.log(paypal.request.post(CREATE_URL));
                            return paypal.request.post(CREATE_URL)
                                .then(function(res) {

                                    return res.paymentID;
                                });
                        },

                        // onAuthorize() is called when the buyer approves the payment
                        onAuthorize: function(data, actions) {

                            // Set up a url on your server to execute the payment
                            var EXECUTE_URL = '/demo/checkout/api/paypal/payment/execute/';

                            // Set up the data you need to pass to your server
                            var data = {
                                paymentID: data.paymentID,
                                payerID: data.payerID
                            };

                            // Make a call to your server to execute the payment
                            return paypal.request.post(EXECUTE_URL, data)
                                .then(function (res) {
                                    window.alert('Payment Complete!');
                                });
                        }

                    }, '#paypal-button-container');
                </script>
            </body>

When I run (click the button) the lightbox pops up for a few seconds and then vanishes. 当我运行(单击按钮)时,灯箱会弹出几秒钟,然后消失。 There is no chance for the person to verify their account and pay. 该人员没有机会验证其帐户并付款。

I've read through all the sdk and can get their sample working no problem. 我已经阅读了所有SDK,可以让他们的示例正常工作。 I think that the payment code return must be wrong or something - any help suggestions how to debug would be really great. 我认为付款代码返回一定是错误的或某些东西-任何有关调试的帮助建议都非常好。

Sorry for the long post. 抱歉,很长的帖子。

The problem could be in multiple places. 问题可能在多个地方。

Can you first check the browser developer logs and see if there is any error? 您可以先检查浏览器开发者的日志,看看是否有任何错误吗?

If you get something like - Failed to load https://www.paypal.com/webapps/hermes/api/logger : Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains the invalid value 'null//null'. 如果收到类似的内容-无法加载https://www.paypal.com/webapps/hermes/api/logger :对预检请求的响应未通过访问控制检查:“ Access-Control-Allow-Origin”标头包含无效值'null // null'。 Origin 'null' is therefore not allowed access. 因此,不允许访问原始“空”。

then try running the page of a server and see if that helps? 然后尝试运行服务器页面,看看是否有帮助?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM