将优惠券添加到Stripe Checkout或allow_promotion_codes:在redirectToCheckout上为true

问题描述

通过对Stripe Checkout的超级更新,我一直在研究地球上的方式我可以在结帐流程中添加优惠券输入。

我知道我可以在Session object上设置allow_promotion_codes: true ...,但是遵循Gatsby implementation之后,我正在使用redirecttocheckout方法,该方法不会接受这些参数。 / p>

您知道一种创建新Session并将其传递给redirecttocheckout方法方法吗?

我看了很久,在网上找不到任何东西可以完成工作+鉴于我的浅薄理解/以上,这听起来很愚蠢...感觉我应该是能够做到。

解决方法

不幸的是,您似乎不能将allow_promotion_codes: true与仅客户端的Checkout一起使用-它仅适用于服务器端实现。

,

TL; DR;您可以在Stripe结帐上允许优惠券代码,您目前要做必须通过后端创建会话来完成此操作,但是这很容易,并且只需要几行JS和后端代码。

要实现这一目标,它需要:

  1. JS到后端的AJAX调用以获取allow_promotion_codes: true的sessionID
  2. redirectToCheckout()的JS从后端获得了sessionID

(而不是仅在JS中直接使用redirectToCheckout()的默认设置。)

以下是使用Javascript和PHP的示例:

前端(JavaScript): (请确保更改“您的条纹产品ID”和“您的AJAX端点”的值,并使用Stripe键启动https://js.stripe.com/v3)。

    // bind the button
    document.getElementById('checkout-button').addEventListener('click',function (e) {

        // stop any normal action (if a link)
        e.preventDefault();

        // retrieve a session ID
        ajax_checkoutsession('YOUR STRIPE PRODUCT ID',function (response) {

            // got errors?
            if (typeof response.checkoutSessionId == undefined){

                // could fallback to sending with redirectToCheckout directly
                // otherwise,backend error

            }

            stripe.redirectToCheckout({
                    sessionId: response.checkoutSessionId,})
            .then(function (result) {


                // if error
                if (result.error) {
                    
                    // If `redirectToCheckout` fails due to a browser or network
                    // error,display the localized error message to your customer.         
                    // deal with error

                }

            })
            .catch(function (err) {
                
            // deal with non-network Stripe error

            });

        },function(err){

            // deal with AJAX error
            
        });

    }


    function ajax_checkoutsession(plan,cb,errcb){

            var data = {
                'action': 'retrieve_checkout_session','plan': plan
            };

            jQuery.ajax({
                  type: "POST",url: 'YOUR AJAX ENDPOINT',"data": data,dataType: 'json',timeout: 20000,success: function(response) {

                    // callback
                    if (typeof cb == "function") cb(response);

                    return response;

                  },error: function(response){ 

                    // callback
                    if (typeof errcb == "function") errcb(response);

                  }

            });

    }

然后,后端php非常简单...(需要Stripe库,您的Stripe密钥和成功/取消URL):

// load vendor files
require(dirname( __FILE__ ) . '/vendor/autoload.php');

// setup Stripe
\Stripe\Stripe::setApiKey('YOUR STRIPE SECRET KEY');

// retrieve plan / product
$plan = 'defaultplan'; if (isset($_POST['plan'])) $plan = sanitize_text_field( $_POST['plan'] );

// build any line items (for now,simply one)
$line_items = [[
    'price' => $plan,'quantity' => 1
]];

// Sign customer up for subscription
// Note we could use: `client_reference_id`,`customer`,or `customer_email` for returning customers
$checkout_session = \Stripe\Checkout\Session::create([
    'success_url' => 'https://yoursite.com/success?session_id={CHECKOUT_SESSION_ID}','cancel_url' => 'https://yoursite.com/cancelled','payment_method_types' => ['card'],'mode' => 'subscription','allow_promotion_codes' => true,'line_items' => $line_items
]);

echo json_encode(['checkoutSessionId' => $checkout_session['id']]);
exit();

注意事项:

  • 如果由于某种原因您的AJAX sessionID生成中断,则您的结帐将无法进行。 (您可以通过回退到原始redirectToCheckout()调用来解决此问题。
  • 上面的示例100%现在适用于订阅((需要适应其他付款方式)

有用的链接: