获取在客户端创建的 PayPal v2 订单的详细信息时出错

Error getting details of PayPal v2 Order created on client side

我有一个包含 3 个页面的会员网站,一个用于展示会员资格(使用我的 PayPal 按钮),一个用于注册表格(用于在我的数据库中添加会员),最后一个页面完成所有这些(说“您现在可以登录”)。

我刚刚关注了 YouTube 上的一个视频,为我的会员添加了 PayPal 按钮,以便在开始填写注册表之前支付金额。

我正在使用 PayPal SDK。这是我的代码:

第一页(帐户-step1.php)

<!DOCTYPE html>
<html lang="en">
 <?php
  // Include HEADER  
  include ("includes/head.php");
  ?>
    <!-- SPECIFIC CSS -->
    <link href="css/booking-sign_up.css" rel="stylesheet">

    <style type="text/css">
    .circle {
      width: 70px;
      height: 70px;
      line-height: 70px;
      border-radius: 50%;
      font-size: 24px;
      color: red;
      text-align: center;
      background: gold;
      font-weight: bold;
    }
    /* Media query for mobile viewport */
    @media screen and (max-width: 400px) {
        #paypal-button-container {
            width: 100%;
        }
    }
        
    /* Media query for desktop viewport */
    @media screen and (min-width: 400px) {
        #paypal-button-container {
            width: 250px;
        }
    }
    </style>
    <script src="https://www.paypal.com/sdk/js?client-id=sb&currency=USD"></script>
</head>

<body>
                
    <header class="header_in clearfix">
        <div class="container">
        <div id="logo">
            <a href="index.php">
                <img src="img/logo_sticky.svg" width="250" height="40" alt="" class="logo_sticky">
            </a>
        </div>
        <?php include ("includes/topmenu.php"); ?>
        <a href="#0" class="open_close">
            <i class="icon_menu"></i><span>Menu</span>
        </a>
        <?php include ("includes/menu.php"); ?>
    </div>
    </header>
    <!-- /header -->
    
    <main class="bg_gray pattern">
        
        <div class="container margin_60_40">        
            <div class="main_title center">
                <span><em></em></span>
                <h2><?php echo _e("Our Subscription Plan"); ?></h2>
                <p>VIP 2021 - 2022</p>
            </div>

            <div class="row justify-content-center">
                <div class="col-lg-12">
                    <div class="sign_up">
                        <div class="head">
                            <div class="title">
                            <h3>1 YEAR SUBSCRIPTION</h3>
                        </div>
                        </div>
                        <!-- /head -->
                        <div class="main text-center" style="font-size:16px;">
                                <p><i class="icon_star"></i> <?php echo _e("VIP Membership Card"); ?> <i class="icon_star"></i></p>
                                <p><i class="icon_star"></i> <?php echo _e("Take advantage of original discounts at all our partners everywhere near you"); ?> <i class="icon_star"></i></p>
                                <p><i class="icon_star"></i> <?php echo _e("Your subscription pays for itself in just 1 or 2 uses of discounts"); ?> <i class="icon_star"></i></p>
                                <p><i class="icon_star"></i> <?php echo _e("Each year your easy-to-use privileges are recharged in the application to make you enjoy again"); ?> <i class="icon_star"></i></p>
                                <p><i class="icon_star"></i> <?php echo _e("Contribute to better nutritional health for our children with $ 1 donated to the Club des petits déjeuners by subscription"); ?> <i class="icon_star"></i></p>
                                <p class="text-center">
                                <center>
                                <div class="circle">20$</div>
                                </center>
                                </p>
                                <hr>
                                <center><div id="paypal-button-container"></div></center>
                        </div>
                    </div>
                    <!-- /box_booking -->
                </div>
                <!-- /col -->

            </div>
            <!-- /row -->
        </div>
        <!-- /container -->
        
    </main>
    <!-- /main -->

    <?php include ("includes/footer.php"); ?>

    <div id="toTop"></div><!-- Back to top button -->
    
    <div class="layer"></div><!-- Opacity Mask Menu Mobile -->
    
    <?php include("includes/signin-modal.php"); ?>
    
    <!-- COMMON SCRIPTS -->
    <script src="js/common_scripts.min.js"></script>
    <script src="js/common_func.js"></script>
    <script src="assets/validate.js"></script>
    <!-- Include the PayPal JavaScript SDK -->
    <script src="https://www.paypal.com/sdk/js?client-id=AeQdfTQ2soaOdV7vgLYyTsnsSC3ptpSJJWFsDGwkTXmQocaCBfYPYWV7mHO-iPGX3_ZiLdCqxmqY9h6H&currency=USD"></script>

    <script>
  paypal.Buttons({
    style: {
    color:   'gold',
    shape:   'pill',
    label:   'pay'
  },
    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: '20.00'
          }
        }]
      });
    },
    
    onApprove: function(data, actions) {
      // This function captures the funds from the transaction.
      return actions.order.capture().then(function() {
        window.location = "transaction-completed.php?&orderID="+data.orderID;

      });
    }
  }).render('#paypal-button-container');
  //This function displays Smart Payment Buttons on your web page.
</script>

</body>
</html>

交易-completed.php

<?php

namespace Sample;

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\OrdersGetRequest;
require 'paypal-client.php';
$orderID = $_GET['orderID'];

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

    // Transaction Details
    $orderID = $response->result->id;
    $email = $response->result->payer->email_address;
    $pre_name = $response->result->payer->given_name;
    $last_name = $response->result->payer->surname;
    $full_name = $pre_name.$last_name;

    // INSERT DATA INTO DATABASE
    include('db_paypal.php'); //CONNECT DATABASE
    // PREPARE AND BIND
    $stmt = $con->prepare("INSERT INTO payments (fullname, orderID) VALUES (?, ?) ");
    $stmt->bind_param("ss", $name, $orderID);
    $stmt->execute();

    //TRY TO EXECUTE QUERY
    if (!$stmt) {
      echo 'Error SQL' .mysqli_error($con);
    }
    else{
      session_start(); //START SESSION
      $_SESSION['orderID'] = $orderID; //STORE orderID INTO SESSION VAR
      header("Location:account-step3.php"); //REDIRECT TO NEXT STEP
    }

    $stmt->close(); //CLOSE STATEMENT
    $con->close(); //CLOSE CONNECTION SQL

  }
}

/**
 *This driver function invokes the getOrder function to retrieve
 *sample order details.
 *
 *To get the correct order ID, this sample uses createOrder to create an order
 *and then uses the newly-created order ID with GetOrder.
 */
if (!count(debug_backtrace()))
{
  GetOrder::getOrder($orderID, true);
}
?>

paypal-client.php

<?php

namespace Sample;

use PayPalCheckoutSdk\Core\PayPalHttpClient;
// GO LIVE \LiveEnvironment
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") ?: "AeQdfTQ2soaOdV7vgLYyTsnsSC3ptpSJJWFsDGwkTXmQocaCBfYPYWV7mHO-iPGX3_ZiLdCqxmqY9h6H";
        $clientSecret = getenv("CLIENT_SECRET") ?: "ECMtmwnFIMs09g_UFAGBAabjkOgykKORvIC9Y9xW2Mn2aZRx0bH7DpHyXDFg3klRkzV9nUI8T6HRI1e8";
        return new SandboxEnvironment($clientId, $clientSecret);
    }
}

db_paypal.php

<?php 

$server = "localhost";
$user = "root";
$password = "password";
$db = "superrabais";

$con = new mysqli($server, $user, $password, $db);
if ($con->connect_error) {
    die("Connection Failed:" . $con->connect_error);
}

 ?>

and Last one 最后注册表格是:account-step2.php

<!DOCTYPE html>
<html lang="en">
 <?php
  // Include HEADER  
  include ("includes/head.php");
  ?>
<?php if (empty($_SESSION['orderID'])) {
echo "<script type='text/javascript'>location.replace('../index.php');</script>";
}else{}
?>
    <!-- SPECIFIC CSS -->
    <link href="css/booking-sign_up.css" rel="stylesheet">
</head>

<body>
                
    <header class="header_in clearfix">
        <div class="container">
        <div id="logo">
            <a href="index.php">
                <img src="img/logo_sticky.svg" width="250" height="40" alt="" class="logo_sticky">
            </a>
        </div>
        <?php include ("includes/topmenu.php"); ?>
        <a href="#0" class="open_close">
            <i class="icon_menu"></i><span>Menu</span>
        </a>
        <?php include ("includes/menu.php"); ?>
    </div>
    </header>
    <!-- /header -->
    
    <main class="bg_gray pattern">
        
        <div class="container margin_60_40">
            <div class="row justify-content-center">
                <div class="col-lg-4">
                    <div class="sign_up">
                        <div class="head">
                            <div class="title">
                            <h3><?php echo _e("Registration") ?></h3>
                        </div>
                        </div>
                        <!-- /head -->
                        <div class="main">
                        <form action="includes/register.php" method="post" id="payment-form">
                        <h6><?php echo _e("Personal details") ?></h6>
                            <div class="form-group">
                                <input class="form-control" placeholder="<?php echo _e("First and Last Name");?>" id="full_name" name="full_name" required>
                                <i class="icon_pencil"></i>
                            </div>
                            <div class="form-group">
                                <input class="form-control" placeholder="<?php echo _e("Apartment (Optional)");?>" id="apartment" name="apartment">
                                <i class="icon_house_alt"></i>
                            </div>
                            <div class="form-group">
                                <input class="form-control" placeholder="<?php echo _e("Adress");?>" id="adress" name="adress" required>
                                <i class="icon_house_alt"></i>
                            </div>
                            <div class="form-group">
                                <input class="form-control" placeholder="<?php echo _e("City");?>" id="city" name="city" required>
                                <i class="icon_house_alt"></i>
                            </div>
                            <div class="form-group">
                                <input class="form-control" placeholder="<?php echo _e("Postal Code");?>" id="postalcode" name="postalcode" maxlength="6" minlength="6" required>
                                <i class="icon_house_alt"></i>
                            </div>
                            <div class="form-group">
                                <input class="form-control" placeholder="<?php echo _e("Phone (888-888-8888)");?>" id="phone" name="phone" type="tel" pattern="[0-9]{3}[0-9]{3}[0-9]{4}" maxlength="10" minlength="10" required>
                                <i class="icon_phone"></i>
                            </div>
                            <div class="form-group">
                                <input class="form-control" placeholder="<?php echo _e("Email Address");?>" id="email" name="email" required>
                                <i class="icon_mail"></i>
                            </div>
                            <div class="form-group add_bottom_15">
                                <input class="form-control" placeholder="<?php echo _e("Password (8 character minimum)");?>" id="password" name="password" minlength="8" required>
                                <i class="icon_lock"></i>
                            </div>
                            <input type="hidden" class="form-control" name="refer" id="refer" value="<?php if(!empty($_SESSION['pid'])){echo $_SESSION['pid'];}else{}?>">
                            <input type="submit" class="btn_1 full-width mb_5" name="submit" value="<?php echo _e("Sign up Now");?>">
                        </form>
                        </div>
                    </div>
                    <!-- /box_booking -->
                </div>
                <!-- /col -->

            </div>
            <!-- /row -->
        </div>
        <!-- /container -->
        
    </main>
    <!-- /main -->

    <?php include ("includes/footer.php"); ?>

    <div id="toTop"></div><!-- Back to top button -->
    
    <div class="layer"></div><!-- Opacity Mask Menu Mobile -->
    
    <?php include("includes/signin-modal.php"); ?>
    
    <!-- COMMON SCRIPTS -->
    <script src="js/common_scripts.min.js"></script>
    <script src="js/common_func.js"></script>
    <script src="assets/validate.js"></script>

</body>
</html>

一切正常,但当我尝试使用我的 Sandbox 个人或企业帐户付款时,出现错误...

这是我得到的错误:

Fatal error: Uncaught PayPalHttp\HttpException: {"name":"RESOURCE_NOT_FOUND","details":[{"location":"path","issue":"INVALID_RESOURCE_ID","description":"Specified resource ID does not exist. Please check the resource ID and try again."}],"message":"The specified resource does not exist.","debug_id":"17a56f649394f","links":[{"href":"https://developer.paypal.com/docs/api/orders/v2/#error-INVALID_RESOURCE_ID","rel":"information_link","method":"GET"}]} in /home/superrab/public_html/beta/vendor/paypal/paypalhttp/lib/PayPalHttp/HttpClient.php:215 Stack trace: #0 /home/superrab/public_html/beta/vendor/paypal/paypalhttp/lib/PayPalHttp/HttpClient.php(100): PayPalHttp\HttpClient->parseResponse(Object(PayPalHttp\Curl)) #1 /home/superrab/public_html/beta/transaction-completed.php(24): PayPalHttp\HttpClient->execute(Object(PayPalCheckoutSdk\Orders\OrdersGetRequest)) #2 /home/superrab/public_html/beta/transaction-completed.php(65): Sample\GetOrder::getOrder('7KM15574UC31371...', true) #3 {main} thrown in /home/superrab/public_html/beta/vendor/paypal/paypalhttp/lib/PayPalHttp/HttpClient.php on line 215

感谢任何帮助

我看到这是一个 client-side 仅用于支付创建和捕获的集成,然后在 client-side 捕获之后,您可以使用服务器端 AI 调用来获取订单的详细信息。这是一个非常奇怪的混合体,有人想知道为什么你没有集成 'Set Up Transaction' 和“捕获交易 on the server side (and paired with the approval JS for a server side integration) 来获得这种健壮性的所有好处,然后你就不需要额外的 API 调用以获取订单的详细信息,因为在 server-side 捕获之后您已经拥有它并且能够自动存储它。基本上,您似乎真的应该切换到那个而不是您尝试做的这种不必要的混合。


但是,如果您坚持做没人推荐的奇怪且不可取的事情,那么像 7KM15574UC313712P 这样的订单 ID 不是由您的 server-side 代码创建的,因此无法通过这种方式访问​​。您可以尝试的是从 purchase_units[0].captures.id 中查找 JS 中成功的捕获 ID(不是订单 ID),并将此实际的 PayPal 交易 ID 传递给您的服务器代码。然后使用它来获取 v2/payment 捕获对象,它将使用不同的 API/SDK 调用——在您的情况下,这个调用:https://github.com/paypal/Checkout-PHP-SDK/blob/develop/lib/PayPalCheckoutSdk/Payments/CapturesGetRequest.php

(但是,理想情况下,整个段落都没有实际意义,您会更加关注第 1 段)