PayPal Orders API Express Checkout - CaptureOrder ID issue

623 Views Asked by At

bit of a beginner with some of this, but I am struggling understanding some of the walk throughs on the Paypal API checkout. I am ok with PHP but not really got round to fully understanding JavaScript* yet.

So, I have got the client side JAvascript for the check out buttons as shown on the Paypal API as follows:

<script>
            paypal.Buttons(
                {
                env: 'sandbox', // sandbox | production
                     commit: true,

                    createOrder: function() {
                        
                      return fetch('samples/AuthorizeIntentExamples/CreateOrder.php', {
                         method: 'post',
                          headers: {
                          'content-type': 'application/json'
                        },
                         })                       
                          .then(function(res) {
                            return res.json();
                          }).then(function(data) {
                            return data.id; // Use the same key name for order ID on the client and server
                          });

                    },
                onApprove: function(data) 
                    {
                      return fetch('samples/AuthorizeIntentExamples/CaptureOrder.php', {
                    method:'post', 
                    headers: {
                      'content-type': 'application/json',
                      'id':data.id
                    },
                    body: JSON.stringify({
                      orderID: data.id
                    })
                  }).then(function(res) {
                    return res.json();
                  }).then(function(details) {
                    alert('Transaction funds captured from ' + details.payer_given_name);
                  })
                }

                }).render('#paypal-button-container');
        </script>

The CreateOrder side of the code is working fine. I receive the JSON with the payment ID etc. However I am struggling to understand how get the OrderID to the CaptureOrder function. The paypal seems to skirt around this and just states "PUT ORDER ID HERE" in the captureOrder function:

        namespace Sample\AuthorizeIntentExamples;

require ($_SERVER['DOCUMENT_ROOT']. '/vendor/autoload.php');
include ($_SERVER['DOCUMENT_ROOT'].'/vendor/paypal/paypal.php');

use PayPalCheckoutSdk\Payments\AuthorizationsCaptureRequest;
use Sample\PayPalClient;

class CaptureOrder
{
    /**
     * Below method can be used to build the capture request body.
     * This request can be updated with required fields as per need.
     * Please refer API specs for more info.
     */
    public static function buildRequestBody()
    {
        return '{
                  "intent": "CAPTURE",
                  "purchase_units": [
                    {
                      "amount": {
                        "currency_code": "GBP",
                        "value": "100.00"
                      }
                    }
                  ]
                }';
    }
    

        /**
         * Below function can be used to capture order.
         * Valid Authorization id should be passed as an argument.
         */
        public static function captureOrder($authorizationId, $debug=false)
        {
            $request = new AuthorizationsCaptureRequest($authorizationId);
            $request->body = CaptureOrder::buildRequestBody();
            $client = PayPalClient::client();
            $response = $client->execute($request);
    
            if ($debug)
            {
               /* print "Status Code: {$response->statusCode}\n";
                print "Status: {$response->result->status}\n";
                print "Capture ID: {$response->result->id}\n";
                print "Links:\n";
                foreach($response->result->links as $link)
                {
                    print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
                }
                // To toggle printing the whole response body comment/uncomment below line */
                echo json_encode($response->result, JSON_PRETTY_PRINT), "\n";
            }
            return $response->result;
        }
    }
    
        /**
         * Driver function for invoking the capture flow.
         */
        if (!count(debug_backtrace()))
        {
           CaptureOrder::captureOrder('ORDER ID HERE', true);
        }

Do I need to store the JSON results of CreateOrder in a SLQ database and call the order number from there to Capture Order or am I missing something and the client side JavaScript* code in the Paypal workflow Posts the orderID onApprove?


UPDATE:

So I have been and played around and I cannot understand why the order ID is not being sent to CaptureOrder when approved.

onApprove: function(data) {
  return fetch('/my-server/capture-paypal-transaction', {
    headers: {
      'content-type': 'application/json'
    },
    **body: JSON.stringify({
      orderID: data.id
    })**
  }).then(function(res) {
    return res.json();
  }).then(function(details) {
    alert('Transaction funds captured from ' + details.payer_given_name);
  })
}

The orderID does not seem to be here, despite the orderID being returned in data.id at the CreateOrder stage.

I get the following error "Uncaught TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body". This is despite follwoing the PayPal documentation.

I then tried POST data in the header

onApprove: function(data) {
      return fetch('/my-server/capture-paypal-transaction', {
        headers: {
          'content-type': 'application/json',
          'id': data.id
        }
      }).then(function(res) {
        return res.json();
      }).then(function(details) {
        alert('Transaction funds captured from ' + details.payer_given_name);
      })
    }

This stopped the uncaught error, but the data sent in post 'id' was undefined. The then caused the API to return "RESOURCE ID NOT FOUND".

I just dont seem to get how the JAvaScript passes the OrderID between the function in CreateOrder and the function in OnApprove.

Trying my best to learn, but I the paypal documentation seems to assume a lot or miss bits out.

0

There are 0 best solutions below