如何使用 Stripe Checkout 获取动态价格?

Mik*_*ick 6 javascript stripe-payments

我在页面上使用 Stripe 进行支付。该页面上有三个项目,每个项目都有一个根据页面上的输入动态设置的价格。我们将它们称为计划 A、B 和 C。我的 Stripe Checkout 成功地使用了硬编码的价格,但我需要根据单击的按钮和该商品的价值将价格传递给 Stripe。

PHP:

<?php require_once('/stripe/init.php');
\Stripe\Stripe::setApiKey('TEST KEY');

$session = new \Stripe\Checkout\Session::create([
    'payment_method_types' => ['card'],
    'line_items' => [[
      'price_data' => [
        'currency' => 'usd',
        'product_data' => [
          'name' => 'Insurance Plan',
        ],
        'unit_amount' => 4000, //need to set this dynamically
      ],
      'quantity' => 1,
    ]],
    'mode' => 'payment',
    'success_url' => 'https://example.com/success',
    'cancel_url' => 'https://example.com/cancel',
  ]);
?>
Run Code Online (Sandbox Code Playgroud)

JS:

<script>
var stripe = Stripe('PUB KEY');
    jQuery('.checkout-button').on('click', function(e) {
        e.preventDefault();
        var price = jQuery(this).find('.price').val(); //need to do something like this
        stripe.redirectToCheckout({
            sessionId: "<?php echo $session->id; ?>"
        });
    });
</script>
Run Code Online (Sandbox Code Playgroud)

本质上,我需要在单击按钮时创建一个 $post 请求,该请求会点击另一个文件 (checkout.php),在该文件中,我将在使用 $post 数据设置价格变量后创建会话。提前致谢!!!

Mik*_*ick 15

尤里卡!这是为其他偶然发现此问题的人提供的解决方案,但 Stripe 网站上根本没有记录该问题。

charge.php 文件

require_once('./php/init.php');

\Stripe\Stripe::setApiKey('sk_test');

$content = json_decode(file_get_contents('php://input'), true);

$name = $content['name'];
$amount = intval($content['amount']*100);

$session = \Stripe\Checkout\Session::create([
    'payment_method_types' => ['card'],
    'line_items' => [[
      'price_data' => [
        'currency' => 'usd',
        'product_data' => [
          'name' => $name,
        ],
        'unit_amount' => $amount,
      ],
      'quantity' => 1,
    ]],
    'mode' => 'payment',
    'success_url' => 'https://example.com/success',
    'cancel_url' => 'https://example.com/cancel',
  ]);

echo json_encode($session);
Run Code Online (Sandbox Code Playgroud)

JavaScript

var stripe = Stripe('pk_test');

    jQuery('.checkout-button').on('click', function() {
        $name = jQuery(this).prev().prev().prev().text();
        $amount = jQuery(this).prev().find('.dollar-amount').text();
      fetch('/charge.php', {
        method: 'POST',
        body: JSON.stringify({
            name: $name,
            amount: $amount
        }),
        headers: {
            'Content-type': 'application/json; charset=UTF-8'
        }
      })
      .then(function(response) {
        return response.json();
      })
      .then(function(session) {
        console.log(session);
        return stripe.redirectToCheckout({ sessionId: session.id });
      })
      .then(function(result) {
        if (result.error) {
          alert(result.error.message);
        }
      })
      .catch(function(error) {
        console.log('Fetch Error :-S', error);
      });
    });
Run Code Online (Sandbox Code Playgroud)


nth*_*ild 8

对于使用 Node.js 的人:

stripe.checkout.sessions.create({
  customer: stripeCustomerId,
  mode: data.mode,
  payment_method_types: [
    'card',
  ],
  success_url: `${MY_DOMAIN}/admin/stripe`,
  cancel_url: `${MY_DOMAIN}/admin/stripe`,
  line_items: [ // all arguments are required
    {
      price_data: {
        unit_amount: 4000,
        currency: 'usd',
        product_data: {
          name: 'Test Product'
        },
      },
      quantity: 1,
    },
  ],
})
Run Code Online (Sandbox Code Playgroud)

您可以在此处阅读有关临时价格的更多信息。您还可以传入price_data结账、发票项目和订阅计划 API。

更新日期:2022 年 7 月

Stripe 文档的链接已更新。


Nol*_*n H 0

您需要将其推迟到客户单击您的某个按钮,而不是在页面呈现期间创建结帐会话。您将从前端向服务器发出请求以创建会话,然后使用可变数量将会话返回给客户端并重定向。

实际上,它是相同的流程,您只需将该4000值替换为请求中提供的值即可。

您可以在此视频中查看此示例(尽管使用 Python 服务器) ,或者与传递付款金额PHP 示例进行比较(这不是使用 Checkout,但服务器请求模式是类似的)。在您的情况下,如果“items”模式不适用,您将传递 like并访问服务器。body: JSON.stringify({amount: 1234}) $body -> amount