首页 > 解决方案 > 使用 Stripe Checkout 允许客户购买产品

问题描述

对于使用 Stripe 的一种非常简单的方法,我还没有找到答案(在我看来)。使用 Stripe Checkout,我如何允许人们为我已经在仪表板的“产品”部分中创建的产品付款?我找到的所有文档都显示了如何检索产品数据等,这很好,但实际上并没有解释如何允许客户使用 Checkout购买产品。我正在使用 PHP,但很高兴看到任何语言的任何示例都遵循这一轨迹。

标签: phpstripe-payments

解决方案


如果您尝试使用checkout.jsor来执行此操作stripe elements,则这是不可能的。您将需要通过以下方式处理此服务器端:

首先获取一个令牌,它代表客户使用Stripe Elements 订阅 提交的卡

脚本:

    $('.btn-save-sub').click(function () {
         //if your customer has chosen a plan, for example 
          var plan = $("#plan_id").val();
          var stripe = Stripe(//your public key here );
          var elements = stripe.elements();

          /**create and mount cc and cc exp elements**/
          var card = elements.create('card'); //complete card element, can be customized
          card.mount('#card-element');

          card.addEventListener('change', function(event) {
               var displayError = document.getElementById('card-errors');
               if (event.error) {
                   displayError.textContent = event.error.message;
               }else{
                   displayError.textContent = '';
               }
            });

           var form = document.getElementById('subscription_add_new_source');

           stripe.createToken(card).then(function(result) {
                if (result.error) {
                    var errorElement = document.getElementById('card-errors');
                    errorElement.textContent = result.error.message;
                }else{
                    //post result.token.id  and plan_id to your server, this token represents the card you will be using 
                }
        });
    });

现在,服务器端您有一个令牌和一个 plan_id(如果您决定允许客户选择一个计划)。现在我们将使用 Stripe 的PHP 绑定为客户订阅该计划

 //you have posted a plan_id to be used, you will create a subscription for that plan id, create a card objecting using the token you have, and attach that card as a default source to the stripe customer

 $stripe_customer= //retrieve it, if you don't have one, create it

通过条带 API 创建客户

拥有客户后,您将首先创建一个卡片对象并将其指定为默认来源:

//create new card
$new_card = $stripe_customer->sources->create(array('sources'=>$posted_token));

//assign newly created card as customer's default source
//subscriptions can only charge default sources 
$stripe_customer->default_source = $new_card->id; 

//finally, create a subscription with the plan_id 
$subscription = \Stripe\Subscription::create(
        array(
            'customer' => $stripe_customer->id,
            'items' => array(
                array(
                    'plan' => $posted_plan_id,       
                )
            ),
            'trial_end' =>$end // represents the first day a  customer will be charged for this plan, pass a timestamp 
        )
    );

推荐阅读