贝宝智能按钮返回我JSON错误 [英] PayPal Smart Buttons returns me JSON error

查看:72
本文介绍了贝宝智能按钮返回我JSON错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PHP(使用PayPal智能按钮)实现Express Checkout集成,但是在尝试付款时出现错误.

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

调用createOrder函数时将触发错误.我相信错误在于服务器端,因为fetch正在成功执行并且服务器生成了ORDER ID,但是它没有正确地将ORDER ID传递给客户端,因此我遇到了以下错误:

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:

错误:位置0的JSON中出现意外的令牌S

Error: Unexpected token S in JSON at position 0

我不知道我使用贝宝(PayPal)提供的SDK可能出什么问题

I don't know what could be wrong as I'm using the SDK provided by 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文档中获得了代码.

I got the code from PayPal documentation.

更新

当我用以下内容替换return $response时:

When I replace return $response with something like this:

 $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直接访问它时,它显示出了点问题".

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

推荐答案

我终于找到了在后端和前端进行一些修改的解决方案.

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

我得到了这个工作

注释这部分代码

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

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

并在前端调整货币

and adjusting the currency as well in the front end

错误的货币选项引发异常,导致PayPal灯箱关闭(以及信用卡选项).

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

这篇关于贝宝智能按钮返回我JSON错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆