首页 > 解决方案 > Stripe - 一键创建/检索客户

问题描述

如果用户不存在,我们是否可以使用条带 API 调用来创建用户并检索新用户?

说我们这样做:

export const createCustomer = function (email: string) {
  return stripe.customers.create({email});
};

即使拥有该电子邮件的用户已经存在,它也会始终创建一个新的客户 ID。 是否存在仅当用户电子邮件不存在于条带中时才会创建用户的方法?

我只是想避免在同一时间范围内可能发生多个呼叫的竞争条件。stripe.customers.create({email})例如,我们检查 customer.id 是否存在,并且不存在,两个不同的服务器请求可能会尝试创建新客户。

这是比赛条件:

const email = 'foo@example.com';

Promise.all([
  stripe.customers.retrieve(email).then(function(user){
   if(!user){
     return stripe.customers.create(email);
   }
  },
 stripe.customers.retrieve(email).then(function(user){
   if(!user){
     return stripe.customers.create(email);
   }
 }
])

显然,竞争条件更有可能发生在两个不同的进程或两个不同的服务器请求中,而不是同一个服务器请求,但你明白了。

标签: stripe-paymentsstripe.js

解决方案


不,在 Stripe 中没有内置的方法可以做到这一点。Stripe 不要求客户的电子邮件地址是唯一的,因此您必须自己验证它。您可以在您自己的数据库中跟踪您的用户并避免重复,或者您可以使用 Stripe API 检查给定电子邮件是否已经存在客户:

let email = "test@example.com";
let existingCustomers = await stripe.customers.list({email : email});
if(existingCustomers.data.length){
    // don't create customer
}else{
    let customer = await stripe.customers.create({
        email : email
    });
}

推荐阅读