首页 文章

条带 - 在一次通话中创建/检索客户

提问于
浏览
2

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

说我们这样做:

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

即使具有该电子邮件的用户已经存在,它也将始终创建新的客户ID . Is there a method that will create a user only if the user email does not exist in stripe?

我只是想避免在同一时间段内可能发生多个 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);
   }
 }
])

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

3 回答

  • 1

    不,在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
        });
    }
    
  • 0

    正如karllekko的评论所提到的,Idempotent Keys不会在这里工作,因为它们只持续24小时 .

    email isn 't a unique field in Stripe; if you want to implement this in your application, you'我需要在你的应用程序中处理它 - 也就是说,你需要存储 [ email -> Customer ID ] 并在那里查找以决定你是否应该创建 .

    假设你的应用程序中有一个 user 对象,那么无论如何这个逻辑会更好地定位在那里,因为你也希望这样做的一部分 - 在这种情况下,每个 user 只会有一个Stripe Customer,所以这个会在其他地方解决 .

  • 2

    如果您的用例类似于您不想使用相同的电子邮件创建两次客户 .

    您可以使用条带幂等请求的概念 . 我用它来避免同一订单的重复费用 .

    您可以使用客户电子邮件作为幂等密钥 . Stripe在最后处理它 . 具有相同幂等密钥的两个请求将不会被处理两次 .

    此外,如果您想在一段时间内限制它,请使用客户电子邮件和该时间范围创建一个幂等密钥 . 它会工作 .

    API支持idempotencycy安全地重试请求,而不会意外地执行两次相同的操作 . 例如,如果由于网络连接错误而导致创建充电的请求失败,则可以使用相同的幂等密钥重试该请求,以保证仅创建一次充电 .

    你可以阅读更多关于这个here的信息 . 我希望这有帮助

相关问题