Ошибка кода примера PayPal Checkout: неожиданный токен <in JSON в позиции 0 - PullRequest
0 голосов
/ 22 января 2020

Вот код, который я использую, который я получил от https://developer.paypal.com/docs/checkout/integrate/

 <script
                src="https://www.paypal.com/sdk/js?client-id=<?= $paypalID; ?>&currency=GBP"> 
              </script>

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

              <script>



                paypal.Buttons({
                    createOrder: function(data, actions) {
                      // This function sets up the details of the transaction, including the amount and line item details.
                      return actions.order.create({
                        purchase_units: [{
                          amount: {

                            "value": "<?= $grandTotalOP; ?>"
                          }
                        }]
                      });
                    },
                    onApprove: function(data) {
                        console.log(data);

                        var theBody = {'orderID' : data.orderID};
                        theBody = JSON.stringify(theBody);

                      return fetch('/capture-paypal-transaction', {
                        headers: {
                          'content-type': 'application/json'
                        },
                        method: "POST",
                        body: theBody
                      }).then(function(res) {
                         console.log('test');
                         console.log(res);
                        return res.json();
                      }).then(function(details) {
                        alert('Transaction funds captured from ' + details.payer_given_name);
                      })
                    }
                  }).render('#paypal-button-container');

              </script>

Я получаю эту ошибку в консоли

js? Client-id = AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe¤cy = GBP: 1 необработанный * 10 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * , (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP: 1: 295788 ) на объекте. (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP: 1: 302957 ) при JSON .parse () при o (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP: 1: 302816 ) при wr (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP: 1: 302969 ) по Ir. Lon (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP: 1: 307996 ) по Ir (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP: 1: 308185 ) при https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP: 1: 313190 в https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP: 1: 313236

Ошибка: неожиданный токен https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP: 1: 295788 ) в массиве. (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP: 1: 302957 ) при JSON .parse () при o (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP: 1: 302816 ) при wr (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP: 1: 302969 ) по Ir. Lon (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP: 1: 307996 ) по Ir (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP: 1: 308185 ) при https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP: 1: 313190 в https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP: 1: 313236

, и это ответ от сервера

Fatal error Uncaught PayPalHttp \ HttpException: {"error": "invalid_client", "error_description": "Ошибка аутентификации клиента"} в /home/MYSERVER/public/vendor/paypal/paypalhttp/lib/PayPalHttp/HttpClient.155 Трассировка стека: # 0 /home/MYSERVER/public/vendor/paypal/paypalhttp/lib/PayPalHttp/HttpClient.php(100): PayPalHttp \ HttpClient-> parseResponse (Объект (PayPalHttp \ Curl) # MYSERVER / public / vendor / paypal / paypal-checkout-sdk / lib / PayPalCheckoutSdk / Core / AuthorizationInjector. php (37): PayPalHttp \ HttpClient-> execute (Object (PayPalCheckoutSdk \ Core \ AccessTokenRequest / home /) / 2) # MYSERVER / государственные / поставщик / PayPal / PayPal-выписка-SDK / Lib / PayPalCheckoutSdk / Cor e / AuthorizationInjector. php (29): PayPalCheckoutSdk \ Core \ AuthorizationInjector-> fetchAccessToken () # 3 /home/MYSERVER/public/vendor/paypal/paypalhttp/lib/PayPalHttp/HttpClient.ckk_Py(ChipS_64D) \ Core \ AuthorizationInjector-> inject (Object (PayPalCheckoutSdk \ Orders \ OrdersGetRequest)) # 4 /home/MYSERVER/public/public/capture-paypal-transaction.php(23): PayPalHttp \ HttpClient- in / home / MYSERVER / public / vendor / paypal / paypalhttp / lib / PayPalHttp / HttpClient. php on line 215

вот код сервера, который взят из ссылки на документацию PayPal вверху

  <?php

namespace Sample;

require_once '/home/MYSERVER/public/vendor/autoload.php'; 

//1. Import the PayPal SDK client that was created in `Set up Server-Side SDK`.
use Sample\PayPalClient;
use PayPalCheckoutSdk\Orders\OrdersGetRequest;

class GetOrder
{

  // 2. Set up your server to receive a call from the client
  /**
   *You can use this function to retrieve an order by passing order ID as an argument.
   */
  public static function getOrder($orderId)
  {

    // 3. Call PayPal to get the transaction details
    $client = PayPalClient::client();
    $response = $client->execute(new OrdersGetRequest($orderId));
    /**
     *Enable the following line to print complete response as JSON.
     */
    //print json_encode($response->result);
    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";
    }
    // 4. Save the transaction in your database. Implement logic to save transaction to your database for future reference.
    print "Gross Amount: {$response->result->purchase_units[0]->amount->currency_code} {$response->result->purchase_units[0]->amount->value}\n";

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

/**
 *This driver function invokes the getOrder function to retrieve
 *sample order details.
 *
 *To get the correct order ID, this sample uses createOrder to create a new order
 *and then uses the newly-created order ID with GetOrder.
 */

if (!count(debug_backtrace()))
{
  GetOrder::getOrder('REPLACE-WITH-ORDER-ID', true);
}
?>

1 Ответ

1 голос
/ 22 января 2020

Это решение

<?php

namespace Sample;

require_once '/home/server/public/vendor/autoload.php'; 

//1. Import the PayPal SDK client that was created in `Set up Server-Side SDK`.
use Sample\PayPalClient;
use PayPalCheckoutSdk\Orders\OrdersGetRequest;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;


ini_set('error_reporting', E_ALL); // or error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');

class PayPalClient
{
    /**
     * Returns PayPal HTTP client instance with environment that has access
     * credentials context. Use this instance to invoke PayPal APIs, provided the
     * credentials have access.
     */
    public static function client()
    {
        return new PayPalHttpClient(self::environment());
    }

    /**
     * Set up and return PayPal PHP SDK environment with PayPal access credentials.
     * This sample uses SandboxEnvironment. In production, use LiveEnvironment.
     */
    public static function environment()
    {
        $clientId = getenv("CLIENT_ID") ?: "CLIENT_ID-here";
        $clientSecret = getenv("CLIENT_SECRET") ?: "CLIENT_SECRET-here";
        return new SandboxEnvironment($clientId, $clientSecret);
    }
}


class GetOrder
{

  // 2. Set up your server to receive a call from the client
  /**
   *You can use this function to retrieve an order by passing order ID as an argument.
   */
  public static function getOrder($orderId)
  {

    echo "testtttt ".$orderId;
    // 3. Call PayPal to get the transaction details
    $client = PayPalClient::client();
    $response = $client->execute(new OrdersGetRequest($orderId));
    /**
     *Enable the following line to print complete response as JSON.
     */
    print json_encode($response->result);
    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";
    }
    // 4. Save the transaction in your database. Implement logic to save transaction to your database for future reference.
    print "Gross Amount: {$response->result->purchase_units[0]->amount->currency_code} {$response->result->purchase_units[0]->amount->value}\n";

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

/**
 *This driver function invokes the getOrder function to retrieve
 *sample order details.
 *
 *To get the correct order ID, this sample uses createOrder to create a new order
 *and then uses the newly-created order ID with GetOrder.
 */
$request_body = file_get_contents('php://input');
$data = json_decode($request_body);
print_r($data);
echo 'order id = '.$data->orderID;
if (!count(debug_backtrace()))
{
  GetOrder::getOrder($data->orderID, true);
}
?>
...