使用Stripe Checkout允许客户购买产品

时间:2018-08-24 15:26:46

标签: php stripe-payments

我还没有找到答案,这应该是使用Stripe的一种非常简单的方法(我认为)。使用Stripe Checkout,如何允许某人支付我在仪表板的“产品”部分中已经创建的产品的费用?我找到的所有文档都显示了如何检索产品数据等,这很好,但是实际上并没有说明如何允许客户使用Checkout 购买产品。我使用的是PHP,但很乐意看到任何语言的示例都遵循该轨迹。

1 个答案:

答案 0 :(得分:1)

如果尝试使用checkout.jsstripe 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(如果您决定允许客户选择一个计划)。现在,我们将使用条纹的PHP Bindings

为客户订阅该计划
 //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

Create customer via stripe 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 
        )
    );