Ruf*_*nne 6 stripe-payments gatsby
随着Stripe Checkout的超级流畅更新,我一直在研究如何在结帐流程中添加优惠券输入。
我知道我可以在Session 对象allow_promotion_codes: true上设置...但是在遵循Gatsby 实现后,我使用的方法不会接受这些参数。redirectToCheckout
您知道创建新会话并将其传递给redirectToCheckout方法的方法吗?
我看了很长时间,在网上找不到任何东西来完成这项工作+鉴于我的肤浅理解/上述内容,这听起来很愚蠢……感觉像是我应该能够做的事情。
小智 6
TL;博士; 您可以在 Stripe 结帐时允许优惠券代码,目前您必须通过后端创建会话来完成此操作,但这非常简单,只需要几行 JS 和后端代码。
为了实现这一目标,需要:
allow_promotion_codes: trueredirectToCheckout()从后端获取一次sessionID(而不是默认直接redirectToCheckout()在 JS 中使用。)
这是一个使用 Javascript 和 PHP 的示例:
前端 (Javascript):(
请务必更改“您的 STRIPE 产品 ID”和“您的 AJAX 端点”值,并https://js.stripe.com/v3使用您的 Stripe 键启动)。
// 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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
然后后端 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();
Run Code Online (Sandbox Code Playgroud)
注意事项:
redirectToCheckout()调用来解决这个问题。有用的链接:
| 归档时间: |
|
| 查看次数: |
4075 次 |
| 最近记录: |