Stripe - create / retrieve customer in one call

混江龙づ霸主 提交于 2019-12-06 05:11:49

No, there is no inbuilt way to do this in Stripe. Stripe does not require that a customer's email address be unique, so you would have to validate it on your side. You can either track your users in your own database and avoid duplicates that way, or you can check with the Stripe API if customers already exist for the given email:

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
    });
}

As karllekko's comment mentions, Idempotent Keys won't work here because they only last 24 hours.

email isn't a unique field in Stripe; if you want to implement this in your application, you'll need to handle that within your application - i.e., you'll need to store [ email -> Customer ID ]s and do a lookup there to decide if you should create or not.

Assuming you have a user object in your application, then this logic would be better located there anyways, as you'd also want to do this as part of that - and in that case, every user would only have one Stripe Customer, so this would be solved elsewhere.

If your use case is like you don't want to create a customer with the same email twice.

You can use the concept of stripe idempotent request. I used it to avoid duplicate charges for the same order.

You can use customer email as an idempotent key. Stripe handles this at their end. the two request with same idempotent key won't get processed twice.

Also if you want to restrict it for a timeframe the create an idempotent key using customer email and that time frame. It will work.

The API supports idempotency for safely retrying requests without accidentally performing the same operation twice. For example, if a request to create a charge fails due to a network connection error, you can retry the request with the same idempotency key to guarantee that only a single charge is created.

You can read more about this here. I hope this helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!