接入 Stripe

如果你的国际业务里包含接受付款服务,那你可能会用到 Stripe


引入 stripe.js

1
<script src="https://js.stripe.com/v3/"></script>

也可以通过 module 的方式引入

1
npm install @stripe/stripe-js

创建 Stripe 实例

通过 Stripe(publishableKey, options?) 方法创建实例

Server 请求得到 publishableKey 以及 client_secret(确认支付时会用到)

1
var stripe = Stripe('pk_test_TYooMQauvdEDq54NiTphI7jx');

如果是使用 module 方式引入,则:

1
2
3
4
5
npm install @stripe/stripe-js

import {loadStripe} from '@stripe/stripe-js';

const stripe = await loadStripe('pk_test_TYooMQauvdEDq54NiTphI7jx');

创建 Elements 实例

Elements 实例可以用来收集一些敏感信息

1
var elements = stripe.elements();

创建 card 类型的 Element

如果是以 card 进行支付,可以通过 elements.create(‘card’,options?) 创建收集 card 信息的 Element

1
var cardElement = elements.create(‘card’);

将 card Element 挂载到 DOM 上

使用 element.mount(domElement) 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!— Mount the instance within a <label> —>
<label>Card
<div id=“card-element”></div>
</label>

<!—
Or create a <label> with a ‘for’ attribute,
referencing the ID of your container.
—>
<label for=“card-element”>Card</label>
<div id=“card-element”></div>

<script>
cardElement.mount(‘#card-element’)’
</script>

监听 Element

1
2
3
4
5
6
7
cardElement.on(‘change’, function(event) {
if (event.complete) {
// enable payment button
} else if (event.error) {
// show validation to customer
}
});

确认支付

stripe.confirmCardPayment(clientSecret,data?,options?)

需要传入 client_secret 以及 payment_method

1
2
3
4
5
6
7
8
9
10
11
12
stripe
.confirmCardPayment(‘{PAYMENT_INTENT_CLIENT_SECRET}’, {
payment_method: {
card: cardElement,
billing_details: {
name: ‘Jenny Rosen’,
},
},
})
.then(function(result) {
// Handle result.error or result.paymentIntent
});

相关文档:

Accept a card payment | Stripe Payments
Stripe: JavaScript SDK documentation & reference

原文作者: dgb8901,yinxing

原文链接: https://www.itwork.club/2020/07/01/use-stripe/

版权声明: 转载请注明出处

为您推荐

体验小程序「简易记账」

关注公众号「特想学英语」

前后端 crypto-js AES 对称加解密