繁体   English   中英

Stripe Checkout 出错:同一页面上的一次性 + 订阅付款按钮?

[英]ERROR with Stripe Checkout: One-Time + Subscription Payment Buttons on the same page?

更新我构建了一个定价页面,该页面使用Stripe Checkout为产品 1 使用一次性付款按钮,为产品 2 使用订阅付款按钮。

在此处输入图像描述

我的目标是通过一次性付款将一次性付款按钮重定向到 Stripe Checkout,并通过定期付款将订阅付款单独重定向到结账。

根据 STRIPE,这可以在 create-checkout-session.php(示例项目)的 CheckoutSession 中使用订阅作为模式来完成:

Checkout 的模式 Session。使用价格或设置模式时需要。 如果结帐 Session 包含至少一项经常性项目,则通过订阅。

与 Stripe 文档相反,以下代码行: 'mode' => 'subscription',仅激活订阅付款,但它不会重定向一次性付款。 要使一次性付款起作用,我必须将其更改为: 'mode' => 'payment',但订阅付款不起作用。

这是有问题的 php 代码:

 <?php
    
    require_once 'shared.php';
    
    $domain_url = $config['domain'];
    
    // Create new Checkout Session for the order
    // Other optional params include:
    // [billing_address_collection] - to display billing address details on the page
    // [customer] - if you have an existing Stripe Customer ID
    // [payment_intent_data] - lets capture the payment later
    // [customer_email] - lets you prefill the email input in the form
    // For full details see https://stripe.com/docs/api/checkout/sessions/create
    
    // ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID set as a query param
    $checkout_session = \Stripe\Checkout\Session::create([
        'success_url' => $domain_url . '/success.html?session_id={CHECKOUT_SESSION_ID}',
        'cancel_url' => $domain_url . '/canceled.html',
        'payment_method_types' => ['card'],
        'mode' => 'subscription',
        'line_items' => [[
          'price' => $body->priceId,
          'quantity' => 1,
      ]]
    ]);
    
    echo json_encode(['sessionId' => $checkout_session['id']]);

这是 javascript 代码:

// Create a Checkout Session with the selected plan ID
var createCheckoutSession = function(priceId) {
  return fetch("./create-checkout-session.php", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      priceId: priceId
    })
  }).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("./config.php")
  .then(function(result) {
    return result.json();
  })
  .then(function(json) {
    var publishableKey = json.publishableKey;
    var subscriptionPriceId = json.subscriptionPrice;
    var onetimePriceId = json.onetimePrice;

    var stripe = Stripe(publishableKey);
    // Setup event handler to create a Checkout Session when button is clicked
    document
      .getElementById("subscription-btn")
      .addEventListener("click", function(evt) {
        createCheckoutSession(subscriptionPriceId).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("onetime-btn")
      .addEventListener("click", function(evt) {
        createCheckoutSession(onetimePriceId).then(function(data) {
          // Call Stripe.js method to redirect to the new Checkout page
          stripe
            .redirectToCheckout({
              sessionId: data.sessionId
            })
            .then(handleResult);
        });
      });
      
  });

使用 Stripe Checkout 甚至可以在同一页面上同时进行一次性付款和定期付款吗? 我怎样才能做到这一点?

根据 Bemn更新

$checkout_session = \Stripe\Checkout\Session::create([
  'success_url' => $domain_url . '/success.html?session_id={CHECKOUT_SESSION_ID}',
  'cancel_url' => $domain_url . '/canceled.html',
  'payment_method_types' => ['card'],
  'mode' => $body->mode
    'line_items' => [[
    'price' => $body->price_xxx,
    // For metered billing, do not pass quantity
    'quantity' => 1,
  ]],

  'line_items' => [[
    'price' => $body->price_zzz,
    // For metered billing, do not pass quantity
    'quantity' => 1,
  ]]
]);

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

和 JS:

// Create a Checkout Session with the selected plan ID
var createCheckoutSession = function(priceId, mode) {
  return fetch("./create-checkout-session.php", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      priceId: priceId,
      mode: mode // <-- passing the mode, e.g. 'payment' or 'subscription'
    })
  }).then(function(result) {
    return result.json();
  });
};

和 HTML:

<div data-stripe-priceid="pricexxx" data-stripe-mode="payment" id="onetime-btn" class="bold mt-2 d-inline-block w-100-after-md max-width-xxs py-2 btn btn-secondary">Ore Time</div>
    
<div data-stripe-priceid="pricexxx" data-stripe-mode="subscription" id="subscription-btn" class="bold mt-2 d-inline-block w-100-after-md max-width-xxs py-2 btn btn-secondary">Ore Time</div>

甚至可以使用 Stripe Checkout 在同一页面上同时进行一次性付款和定期付款吗?

是的。 关键是您应该传递正确的选项来生成相应的 Stripe Checkout session ID。

我怎样才能做到这一点?

  • 后端:有一个 function 接受Stripe 的价格 ID支付方式作为输入,并返回一个 Stripe Checkout session ID 作为 output。

  • 前端:将支付方式信息传递给/create-checkout-session.php (如果您不能这样做,请参阅注释)


细节

以下解决方案假设:

  1. 您在后端生成一个 Stripe Checkout Session ID。 然后,该 ID 将传递给 js 前端中的.createCheckoutSession()
  2. 您有一个 1-time 产品(我们称之为PAY )和一个定期订阅(我们称之为SUB )。

前端

我认为你很接近。 您需要做的是将mode信息也传递给您的 API 端点:

// Create a Checkout Session with the selected plan ID
var createCheckoutSession = function(priceId, mode) { // <-- add a mode parameter
  return fetch("./create-checkout-session.php", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      priceId: priceId,
      mode: mode // <-- passing the mode, e.g. 'payment' or 'subscription'
    })
  }).then(function(result) {
    return result.json();
  });
};

如果是这样,页面中的每个结帐按钮都应该有相应的 priceId 和付款方式信息。 您可以通过使用 data 属性存储它们来做到这一点:

<div data-stripe-priceid="price_yyy" data-stripe-mode="subscription">Recurrent</div>
<div data-stripe-priceid="price_zzz" data-stripe-mode="payment">1-time</div>

如果是这样,您可以通过例如click事件来获取数据属性。

注意:如果您不能添加额外的参数来指示模式,您需要在后端识别给定的价格 ID 是 1-time 还是经常性产品。 有关详细信息,请参阅https://stripe.com/docs/api/prices/object?lang=php#price_object-type

后端

以下是 Stripe 文档中的 2 个示例代码片段。 直接复制它们是行不通的

PAY参考: https://stripe.com/docs/checkout/integration-builder

$checkout_session = \Stripe\Checkout\Session::create([
  'payment_method_types' => ['card'],
  'line_items' => [[
    'price_data' => [
      'currency' => 'usd',
      'unit_amount' => 2000,
      'product_data' => [
        'name' => 'Stubborn Attachments',
        'images' => ["https://i.imgur.com/EHyR2nP.png"],
      ],
    ],
    'quantity' => 1,
  ]],
  'mode' => 'payment',
  'success_url' => $YOUR_DOMAIN . '/success.html',
  'cancel_url' => $YOUR_DOMAIN . '/cancel.html',
]);

在您的情况下,您可能不需要定义'price_data' 相反,您应该使用'price' ,就像下一个示例一样。

SUB参考: https://stripe.com/docs/billing/subscriptions/checkout#create-session

$checkout_session = \Stripe\Checkout\Session::create([
  'success_url' => 'https://example.com/success.html?session_id={CHECKOUT_SESSION_ID}',
  'cancel_url' => 'https://example.com/canceled.html',
  'payment_method_types' => ['card'],
  'mode' => 'subscription',
  'line_items' => [[
    'price' => $body->priceId,
    // For metered billing, do not pass quantity
    'quantity' => 1,
  ]],
]);
  1. 看看这个参考: https://stripe.com/docs/api/checkout/sessions/create 对于line_items ,您可以简单地使用'price'并传递价格 ID(例如price_xxx ),这意味着您'line_items'将如下所示:
'line_items' => [[
  'price' => $body->priceId,
  'quantity' => 1,
]],

对于'mode' ,使用 API 请求中的值。 它应该是这样的:

'mode' => $body->mode

这意味着在您的后端,您最好将 function (例如generate_checkout_session )定义为:

  • 解析在 API 请求中收到的 json 正文
  • 从解析的数据中获取priceIdmode
  • \Stripe\Checkout\Session::create中使用priceIdmode
  • 返回checkout_session ID

希望这(和参考网址)可以帮助你。

当您创建 Session 时,您可以同时传递一个价格来表示订阅收取的经常性金额,也可以传递另一个价格来表示您想要收取的一次性费用。 您可以整体组合多个经常性价格和一次性价格。

$checkout_session = \Stripe\Checkout\Session::create([
    'success_url' => $domain_url . '/success.html?session_id={CHECKOUT_SESSION_ID}',
    'cancel_url' => $domain_url . '/canceled.html',
    'payment_method_types' => ['card'],
    'mode' => 'subscription',
    'line_items' => [
      // Add a one-time Price for $10
      [
        'price' => 'price_123', 
        'quantity' => 1,
      ],
      // Add another one-time Price for $23
      [
        'price' => 'price_345', 
        'quantity' => 1,
      ],
      // Add a recurring Price for $100 monthly
      [
        'price' => 'price_ABC', 
        'quantity' => 1,
      ],
]);

上面的代码将创建一个包含 3 个行项目的 session。 一种每月 100 美元,一种只需 10 美元一次,另一种只需 23 美元一次。 session 的第一次付款总额为 133 美元。 它还将开始以每月 100 美元的价格订阅,未来的发票将按预期收取 100 美元。

我所得到的是,您只需要添加一张支票,无论是一次性的还是订阅,您都可以这样做:

JS FILE CHANGES:

var createCheckoutSession = function(priceId, $mode) {
  return fetch("./create-checkout-session.php", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      priceId: priceId,
      paymentType: $mode, // This vary based on the button clicked either one-time or subscription.
    })
  }).then(function(result) {
    return result.json();
  });
};

/* Get your Stripe publishable key to initialize Stripe.js */
fetch("./config.php")
  .then(function(result) {
    return result.json();
  })
  .then(function(json) {
    var publishableKey = json.publishableKey;
    var subscriptionPriceId = json.subscriptionPrice;
    var onetimePriceId = json.onetimePrice;

    var stripe = Stripe(publishableKey);
    // Setup event handler to create a Checkout Session when button is clicked
    document
      .getElementById("subscription-btn")
      .addEventListener("click", function(evt) {
        createCheckoutSession(subscriptionPriceId, 'subscription').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("onetime-btn")
      .addEventListener("click", function(evt) {
        createCheckoutSession(onetimePriceId, 'onetime').then(function(data) {
          // Call Stripe.js method to redirect to the new Checkout page
          stripe
            .redirectToCheckout({
              sessionId: data.sessionId
            })
            .then(handleResult);
        });
      });
      
  });

现在我们需要在 PHP 文件中进行更改:

PHP FILE CHANGES:

$checkout_session = \Stripe\Checkout\Session::create([
        'success_url' => $domain_url . '/success.html?session_id={CHECKOUT_SESSION_ID}',
        'cancel_url' => $domain_url . '/canceled.html',
        'payment_method_types' => ['card'],
        'mode' => $body->paymentType, // Here is what we have got from front-end
        'line_items' => [[
          'price' => $body->priceId,
          'quantity' => 1,
      ]]
    ]);

对于订阅我们实际上需要设置间隔,这是不需要一次性设置的。 可能由于这个原因发生了这个错误。 添加循环可以解决循环错误。

recurring: {
   interval: 'month' // 'month' | 'year'
}

暂无
暂无

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

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