简体   繁体   English

Stripe:从 HTML 到 Checkout-Sessions PHP 的元数据

[英]Stripe: Meta Data from HTML to Checkout-Sessions PHP

I use the samples ( https://github.com/stripe-samples/checkout-single-subscription/tree/master/server/php ) from Stripe to create a subscription.我使用 Stripe 中的示例 ( https://github.com/stripe-samples/checkout-single-subscription/tree/master/server/php ) 创建订阅。 What I don't really understand, how can I pass metadata from my index.html over script.js to the create-checkout-session.php.我不太明白的是,如何通过 script.js 将元数据从我的 index.html 传递到 create-checkout-session.php。

I thought I just add data attributes to the index.html:我以为我只是将数据属性添加到 index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Stripe</title>
    <meta name="description" content="A demo of Stripe Payment Intents" />
    <link rel="icon" href="favicon.ico" type="image/x-icon" />
    <script src="https://js.stripe.com/v3/"></script>
    <script src="./script.js" defer></script>
  </head>
  <body>
    <div class="sr-root">
      <div class="sr-main" style="display: flex;">
        <div class="sr-container">
          <section class="container">
            <button id="basic-plan-btn" data-partner="name" data-package="basic">USD 6.90</button>
          </section>
          <section class="container">
            <button id="pro-plan-btn" data-partner="name" data-package="premium">USD 11.90</button>
          </section>
        </div>
      </div>
    </div>
  </body>
</html>

then I have to read them somehow out in the script.js.然后我必须以某种方式在 script.js 中读取它们。 But that I don't really figure out how.但我真的不知道怎么做。

// Create a Checkout Session with the selected plan ID
var createCheckoutSession = function(priceId) {
  return fetch("/fileadmin/restaurant/stripe/create-checkout-session.php", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      priceId: priceId,
      partner: 'name',
      package: 'premium'
    })
  }).then(function(result) {
    return result.json();
  });
};

// Handle any errors returned from Checkout
var handleResult = function(result) {
  if (result.error) {
    var displayError = document.getElementById("error-message");
    displayError.textContent = result.error.message;
  }
};

/* Get your Stripe publishable key to initialize Stripe.js */
fetch("/fileadmin/restaurant/stripe/config.php")
  .then(function(result) {
    return result.json();
  })
  .then(function(json) {
    var publishableKey = json.publishableKey;
    var basicPriceId = json.basicPrice;
    var proPriceId = json.proPrice;

    var stripe = Stripe(publishableKey);
    // Setup event handler to create a Checkout Session when button is clicked
    document
      .getElementById("basic-plan-btn")
      .addEventListener("click", function(evt) {
        createCheckoutSession(basicPriceId).then(function(data) {
          // Call Stripe.js method to redirect to the new Checkout page
          stripe
            .redirectToCheckout({
              sessionId: data.sessionId
            })
            .then(handleResult);
        });
      });

    // Setup event handler to create a Checkout Session when button is clicked
    document
      .getElementById("pro-plan-btn")
      .addEventListener("click", function(evt) {
        createCheckoutSession(proPriceId).then(function(data) {
          // Call Stripe.js method to redirect to the new Checkout page
          stripe
            .redirectToCheckout({
              sessionId: data.sessionId
            })
            .then(handleResult);
        });
      });
  });

by that I receive them in the create-checkout-session.php这样我就在 create-checkout-session.php 中收到了它们

<?php
require_once 'shared.php';
$domain_url = $config['domain'];
$checkout_session = \Stripe\Checkout\Session::create([
    'success_url' => $domain_url . 'success.php?session_id={CHECKOUT_SESSION_ID}',
    'cancel_url' => $domain_url . 'canceled.php',
    'payment_method_types' => ['card'],
    'mode' => 'subscription',
    'allow_promotion_codes' => true,
    'line_items' => [[
      'price' => $body->priceId,
      'quantity' => 1,
    ]],
    'subscription_data' => ['trial_period_days' => 60],
    'metadata' => [
        'partner' => $body->partner,
        'package' => $body->package
    ],
]);
echo json_encode(['sessionId' => $checkout_session['id']]);

Thank You.谢谢你。

What you've done adding to the JSON body of the fetch call looks right to me.您在fetch调用的 JSON 主体中所做的添加在我看来是正确的。 If you're trying to set the 'name' and 'premium' values dynamically from some input, then take a look at this previous answer for some approaches for getting input values.如果您尝试根据某些输入动态设置'name''premium'值,请查看之前的答案以获取一些获取输入值的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM