Stripe subscription payments and WebHook events

(Where there is a genius, I spend all the time others spend drinking coffee on my work. - Lu Xun)

insert image description here

stripe

Stripe was founded by two brothers Patrick Collison and John Collison in their 20s. Stripe provides companies with online payment solutions. Stripe charges companies it serves 2.9 percent of each transaction plus a 30-cent fee

Example code for subscribing to payment and WebHook events

  • The subscription payment adopts the official SDK provided by Stripe, which saves the front-end payment page development work
  • For event push, just add the path under the stripe account, but you need to select the corresponding event type

For methods such as using the test bank card number, please refer to the official test card number provided by stripe

import Stripe from 'stripe';

class StripeSubscribeService {
    
    
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  constructor() {
    
    }

  // 获取stripe订阅支付链接
  async getStripeSubscribeUrl() {
    
    
    // stripe账户秘钥
    const STRIPE_ACCOUNT_SK = 'sk_test_xxxxx';
    // stripe支付成功后的重定向页面
    const STRIPE_REDIRECT_DOMAIN = 'http://localhost:8000';
    // 实例化stripe对象
    const stripe = new Stripe(STRIPE_ACCOUNT_SK, {
    
     apiVersion: '2022-11-15' });
    // 获取stripe订阅支付链接
    // 这里直接使用stripe提供的sdk链接
    const result = await stripe.checkout.sessions.create({
    
    
      // 类型固定为支付卡片
      payment_method_types: ['card'],
      // price为stripe账户下产品的价格id
      // quantity为支付的数量
      line_items: [
        {
    
    
          price: 'price_xxxx',
          quantity: 1,
        },
      ],
      // 支付的类型 subscription为订阅支付
      mode: 'subscription',
      // 支付成功后跳转链接 可以是自己前端服务的链接
      success_url: `${
      
      STRIPE_REDIRECT_DOMAIN}/dashboard/setting/subscribe`,
      // 取消支付后跳转链接
      cancel_url: `${
      
      STRIPE_REDIRECT_DOMAIN}/dashboard/setting/subscribe`,
      // 订阅支付的自定义参数,用于后端服务做额外处理,比如记录日志,更改系统内部状态呢个
      subscription_data: {
    
    
        metadata: {
    
    
          name: 'test',
          id: 'testId',
          env: 'local',
        },
      },
    });
    // stripe订阅支付链接
    console.log(result.url);
  }

  async brandSubscribeWebHook(metadata: any) {
    
    
    const env = metadata.env;
    // 在stripe添加webhook事件,每次支付成功后都会发起调用
    // stripe的事件无法做环境区分,所以我们需要在subscription_data中加入环境参数,这样每次收到后可以根据环境进行区分处理
    if (env !== 'local') {
    
    
      console.log('brandSubscribeWebHook env different', {
    
    
        env,
      });
      return;
    }
  }
}

Guess you like

Origin blog.csdn.net/qq_42427109/article/details/132133495