PayPal Smart Buttons возвращает ошибку JSON - PullRequest
1 голос
/ 24 апреля 2020

Я внедряю Express Интеграция Checkout в PHP (с использованием интеллектуальных кнопок PayPal), но при попытке оплаты я получаю сообщение об ошибке.

Ошибка срабатывает, когда функция createOrder называется. Я полагаю, что ошибка лежит на стороне сервера, потому что fetch выполняется успешно, и сервер генерирует идентификатор ORDER, однако он не передает идентификатор ORDER клиенту должным образом, и в результате я получаю следующую ошибку:

Ошибка: неожиданный токен S в JSON в позиции 0

Я не знаю, что может быть не так, поскольку я использую SDK, предоставленный PayPal

Мой клиент

 <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>

Мой сервер

<?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);
}
?>

Я получил код из документации PayPal.

ОБНОВЛЕНИЕ

Когда я заменяю return $response с чем-то вроде этого:

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

и удалите эту часть кода:

  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);
        }

, это частично работает. Открывается лайтбокс PayPal с созданным токеном, однако сразу после этого закрывается. Когда я пытаюсь получить к нему доступ напрямую, используя URL-адрес, он говорит: «Что-то пошло не так».

1 Ответ

1 голос
/ 24 апреля 2020

Я, наконец, нашел решение, сделав некоторые изменения во внутреннем и переднем концах.

Я получил эту работу,

комментируя эту часть кода

  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);
    }

заменив return $response на

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

и скорректировав также валюту в интерфейсе

Неправильный вариант валюты вызывал исключение, вызывая закрытие лайтбокса PayPal (также как вариант кредитной карты).

...