Stripe-as-promised 是一个 Node.js 库,提供了一个承诺(Promise)接口来与 Stripe 支付服务进行交互。在使用该库之前,需要先在 Stripe 上创建一个账号,并获得 API 密钥。本文将详细介绍 stripe-as-promised 的使用方法。
安装
使用 npm 进行安装:
npm install stripe-as-promised
初始化
在使用 stripe-as-promised 之前,需要先初始化 Stripe:
const stripe = require('stripe')('your_api_key'); const stripePromise = require('stripe-as-promised')(stripe);
这里,我们先通过 require
引入 stripe
模块,并传入 API 密钥。然后使用 stripe-as-promised
(以下简称 SAP)初始化 stripePromise
。
创建一个新客户
首先,让我们创建一个新客户:
const customerData = { email: 'customer@example.com' }; stripePromise.customers.create(customerData) .then(customer => console.log('Customer created:', customer.id)) .catch(error => console.error(error));
这里,我们使用 stripePromise.customers.create
方法来创建一个新客户。该方法返回一个 Promise 对象,我们可以在 .then
中获取创建成功的客户信息,或者在 .catch
中获取错误信息。
添加信用卡
创建客户后,我们可以为该客户添加一张信用卡:
-- -------------------- ---- ------- ----- -------- - - ------- ------------------- ---------- --- --------- ----- ---- ----- -- ------------------------------------------------ - ------- -------- -- ---------- -- ----------------- -------- --------- ------------ -- ----------------------展开代码
这里,我们使用 stripePromise.customers.createSource
方法来为客户添加新的支付来源(payment source),即信用卡。该方法同样返回一个 Promise 对象。
创建一个新订单
现在,让我们使用已添加的信用卡创建一个新订单:
-- -------------------- ---- ------- ----- --------- - - ------- ----- --------- ------ --------- ----------- ------- ------ -- --------------------------------------- ------------ -- ------------------- ---------- ----------- ------------ -- ----------------------展开代码
这里,我们使用 stripePromise.charges.create
方法来创建一个新的订单。该方法同样返回一个 Promise 对象。
总结
以上就是 stripe-as-promised 的使用方法,通过使用承诺接口(Promise)发送请求,可以更加方便地与 Stripe 服务进行交互。希望本文能为你提供有价值的指导和帮助。
完整代码示例:
-- -------------------- ---- ------- ----- ------ - ---------------------------------- ----- ------------- - -------------------------------------- ----- ------------ - - ------ ---------------------- -- --- ----------- --- ------- -------------------------------------------- -------------- -- - --------------------- ---------- ------------- ---------- - ------------ ----- -------- - - ------- ------------------- ---------- --- --------- ----- ---- ----- -- ------ ------------------------------------------------ - ------- -------- --- -- ---------- -- - ----------------- -------- --------- ------ - -------- ----- --------- - - ------- ----- --------- ------ --------- ----------- ------- ------ -- ------ ---------------------------------------- -- ------------ -- ------------------- ---------- ----------- ------------ -- ----------------------展开代码
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/5eedcb24b5cbfe1ea0612558