【问题标题】:How can I use Stripe Checkout with dynamic prices?如何使用动态价格的 Stripe Checkout?
【发布时间】:2021-05-21 18:13:24
【问题描述】:

我在页面上使用 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',
  ]);
?>

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>

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

【问题讨论】:

    标签: stripe-payments


    【解决方案1】:

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

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

    您可以在 this video 中看到一个示例(尽管使用 Python 服务器),或者与 passing a payment amountPHP example 进行比较(这不是使用 Checkout,但服务器请求模式是类似的)。在您的情况下,如果“项目”模式不适用,您会通过 like body: JSON.stringify({amount: 1234}) 并使用 $body -&gt; amount 访问服务器。

    【讨论】:

    • 谢谢,但仍在为此苦苦挣扎……我是否在做一些非正统的事情,没有针对我的特定用例的任何文档?我认为这是非常标准的。如何在不重新加载页面的情况下将该数据转换为 JSON?
    • 这不是页面重新加载,而是来自客户端的异步服务器请求。后两个链接指向一个示例,显示客户端 JS 代码和服务器 PHP 以访问 JSON 正文。如果您有任何其他来自用户操作的服务器请求,这将具有相同的想法。
    • Nolan 感谢您迄今为止的帮助。这让我找到了正确的道路。本质上,我需要在点击另一个文件 (checkout.php) 的按钮单击时创建一个 $post 请求,并且在该文件中,我将在使用 $post 数据设置价格变量后创建会话。我以前用 ajax 做过类似的事情,但我把信息拉回页面。这让我很困惑,因为它在 checkout.php 文件上运行脚本,然后直接重定向到 Stripe 上的结帐。
    【解决方案2】:

    尤里卡!这是其他任何偶然发现此问题的人的解决方案,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);
    

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

    【讨论】:

      【解决方案3】:

      对于使用 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,
          },
        ],
      })
      

      您可以阅读更多关于特设价格的信息here。您还可以将 price_data 传递到 Checkout、Invoice Items 和 Subscription Schedule API。

      【讨论】:

        猜你喜欢
        • 2020-12-04
        • 2021-01-24
        • 1970-01-01
        • 2022-08-13
        • 2017-05-23
        • 2015-11-07
        • 2020-10-05
        • 2018-02-08
        • 2022-01-23
        相关资源
        最近更新 更多