Использование Stripe Checkout, чтобы позволить покупателю приобрести продукт - PullRequest
0 голосов
/ 24 августа 2018

Мне еще предстоит найти ответ на вопрос, каким должен быть очень простой подход к использованию Stripe (на мой взгляд). Как с помощью Stripe Checkout я могу позволить человеку оплачивать продукт, который я уже создал в разделе «Продукты» на панели инструментов? Вся документация, которую я нашел, показывает, как получить данные о продукте и т. Д., И это здорово, но на самом деле это не объясняет, как позволить клиенту купить продукт с Checkout. Я использую PHP, но был бы очень рад увидеть примеры на любом языке, которые следуют этой траектории.

1 Ответ

0 голосов
/ 24 августа 2018

Если вы пытаетесь сделать это, используя checkout.js или 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 (если вы решили позволить клиенту выбрать план). Теперь мы подпишем клиента на план, используя 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

Создание клиента с помощью 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 
        )
    );
...