PayPal Smart Buttons returns me JSON error

醉酒当歌 提交于 2021-02-08 05:41:49

问题


I'm implementing Express Checkout Integration in PHP (using PayPal Smart Buttons) but I get an error when I try to pay.

The error is triggered when the createOrder function is called. I believe the error lies in the server side, because the fetch is being executed successfully and the server generates an ORDER ID, however it does not properly pass the ORDER ID to the client and I end up with the following error:

Error: Unexpected token S in JSON at position 0

I don't know what could be wrong as I'm using the SDK provided by PayPal

My client

 <script>
        // Render the PayPal button into #paypal-button-container
        paypal.Buttons({

            // Set up the transaction
            createOrder: function(data, actions) {
                return fetch('*http://localhost/test/createorder.php', {
                    method: 'post'
                }).then(function(res) {
                    return res.json();
                }).then(function(data) {
                    return data.orderID;
                });
            },

            // Finalize the transaction
            onApprove: function(data, actions) {
                return fetch('https://api.sandbox.paypal.com/v2/checkout/orders/' + data.orderID + '/capture/', {
                    method: 'post'
                }).then(function(res) {
                    return res.json();
                }).then(function(details) {
                    // Show a success message to the buyer
                    alert('Transaction completed by ' + details.payer.name.given_name + '!');
                });
            },
            onError: function(err){
                    alert(err)
            }


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

My server

<?php

namespace Sample\CaptureIntentExamples;

require __DIR__ . '/vendor/autoload.php';
//1. Import the PayPal SDK client that was created in `Set up Server-Side SDK`.
use Sample\PayPalClient;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;

class CreateOrder
{

// 2. Set up your server to receive a call from the client
  /**
   *This is the sample function to create an order. It uses the
   *JSON body returned by buildRequestBody() to create an order.
   */
  public static function createOrder($debug=false)
  {
    $request = new OrdersCreateRequest();
    $request->prefer('return=representation');
    $request->body = self::buildRequestBody();
   // 3. Call PayPal to set up a transaction
    $client = PayPalClient::client();
    $response = $client->execute($request);
    if ($debug)
    {
      print "Status Code: {$response->statusCode}\n";
      print "Status: {$response->result->status}\n";
      print "Order ID: {$response->result->id}\n";
      print "Intent: {$response->result->intent}\n";
      print "Links:\n";
      foreach($response->result->links as $link)
      {
        print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
      }

      // To print the whole response body, uncomment the following line
      // echo json_encode($response->result, JSON_PRETTY_PRINT);
    }

    // 4. Return a successful response to the client.
    return $response;
  }

  /**
     * Setting up the JSON request body for creating the order with minimum request body. The intent in the
     * request body should be "AUTHORIZE" for authorize intent flow.
     *
     */
    private static function buildRequestBody()
    {
        return array(
            'intent' => 'CAPTURE',
            'application_context' =>
                array(
                    'return_url' => 'https://example.com/return',
                    'cancel_url' => 'https://example.com/cancel'
                ),
            'purchase_units' =>
                array(
                    0 =>
                        array(
                            'amount' =>
                                array(
                                    'currency_code' => 'USD',
                                    'value' => '220.00'
                                )
                        )
                )
        );
    }
}


/**
 *This is the driver function that invokes the createOrder function to create
 *a sample order.
 */
if (!count(debug_backtrace()))
{
  CreateOrder::createOrder(true);
}
?>

I got the code from PayPal documentation.

UPDATE

When I replace return $response with something like this:

 $orderID=['orderID'=>$response->result->id];
 echo json_encode($orderID, true);

and remove this part of the code:

  if ($debug)
        {
          print "Status Code: {$response->statusCode}\n";
          print "Status: {$response->result->status}\n";
          print "Order ID: {$response->result->id}\n";
          print "Intent: {$response->result->intent}\n";
          print "Links:\n";
          foreach($response->result->links as $link)
          {
            print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
          }

          // To print the whole response body, uncomment the following line
          // echo json_encode($response->result, JSON_PRETTY_PRINT);
        }

it partially works. The PayPal lightbox opens up with the generated token, however it closes down right after. When I try to access it directly using the URL, it says "Something went wrong".


回答1:


I finnaly found a solution making some modifications in the back end and the front end.

I got this working by

commenting this part of the code

  if ($debug=true)
    {
      print "Status Code: {$response->statusCode}\n";
      print "Status: {$response->result->status}\n";
      print "Order ID: {$response->result->id}\n";
      print "Intent: {$response->result->intent}\n";
      print "Links:\n";
      foreach($response->result->links as $link)
      {
        print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
      }

      // To print the whole response body, uncomment the following line
      // echo json_encode($response->result, JSON_PRETTY_PRINT);
    }

replacing return $response with

$json_obj= array('id'=>$response->result->id);
$jsonstring = json_encode($json_obj);
echo $jsonstring;

and adjusting the currency as well in the front end

The wrong currency option was throwing an exception, causing the PayPal lightbox to close (as well as the credit card option).



来源:https://stackoverflow.com/questions/61410133/paypal-smart-buttons-returns-me-json-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!