简体   繁体   中英

PHP PayPal Server side REST API

I'm playing about with the paypal rest API and I can't get it to work.

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. 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'. Origin 'null' is therefore not allowed access.

then try running the page of a server and see if that helps?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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