条纹付款-将篮子价格传递给PHP中的checkout_session

时间:2020-11-10 15:45:46

标签: stripe-payments integration payment

我正在尝试按照分条站点上的说明创建付款系统。我正在使用PHP。我让系统使用其默认代码。但是,我需要将自己的价格传递给create_session.php。我曾经尝试过简单变量和会话变量,但是每当我用变量替换硬编码数字时,结帐按钮就会停止工作。

您将看到第一行将预定义的会话变量转换为包含我的商品价格的变量。然后将其称为单位金额。

如果我改用2000作为单位金额(即硬编码的原始值),它将起作用。那么我该如何传递动态价格呢?

这是我的代码。

$price = $_SESSION['stripe_total'];

require 'vendor/autoload.php';
\Stripe\Stripe::setApiKey('MY_API_GOES_HERE');

header('Content-Type: application/json');

$YOUR_DOMAIN = 'http://MY_SITE_HERE.co.uk/';


$checkout_session = \Stripe\Checkout\Session::create([
  'payment_method_types' => ['card'],
  'line_items' => [[
    'price_data' => [
      'currency' => 'gbp',
      'unit_amount' => $price,
      'product_data' => [
        'name' => 'Prize draw entries from Speedwinners',
      ],
    ],
    'quantity' => 1,
  ]],
  'mode' => 'payment',
  'success_url' => $YOUR_DOMAIN . '/success.html',
  'cancel_url' => $YOUR_DOMAIN . '/cancel.html',
]);

echo json_encode(['id' => $checkout_session->id]);

添加

所以我认为问题在于如何将price变量传递到create session文件中。我通过设置$ price = 2000进行了测试;在文件本身中,效果很好。

因此-我感到困惑的是如何将价格变量从页面获取到文件中。

调用会话的JS是

<script type="text/javascript">
    // Create an instance of the Stripe object with your publishable API key
    var stripe = Stripe("MY_KEY");
    var checkoutButton = document.getElementById("checkout-button");

    checkoutButton.addEventListener("click", function () {
      fetch("/create-session.php", {
        method: "POST",
      })
        .then(function (response) {
          return response.json();
        })
        .then(function (session) {
          return stripe.redirectToCheckout({ sessionId: session.id });
        })
        .then(function (result) {
          // If redirectToCheckout fails due to a browser or network
          // error, you should display the localized error message to your
          // customer using error.message.
          if (result.error) {
            alert(result.error.message);
          }
        })
        .catch(function (error) {
          console.error("Error:", error);
        });
    });
  </script>

,结帐页面上的代码为

<section>
      <div class="product">
        <div class="description">
          <h3>Total ticket price</h3>
          <h5>£5.00</h5>
        </div>
      </div>
      <button id="checkout-button">Checkout</button>
</section>

0 个答案:

没有答案