I have an array of customers for which I want to bulk charge them in stripe. Sometimes due to network, some charges don't go through while some do therefore making a new request charges all customers again. I read that I could use idempotency but noticed the key regenerates each time I make a request. How do I implement generating the key to identify each user without storing the key in the DB since it is meant to be a temporary key?
for(customer in customers){
stripe.charges.create({
amount: 2000,
currency: "usd",
source: token,
customer: stripe_customerId,
}, {
idempotency_key: uuid
}, function(err, charge) {
// asynchronously called
});
}
Any ideas on this, please?
I have an array of customers for which I want to bulk charge them in stripe. Sometimes due to network, some charges don't go through while some do therefore making a new request charges all customers again. I read that I could use idempotency but noticed the key regenerates each time I make a request. How do I implement generating the key to identify each user without storing the key in the DB since it is meant to be a temporary key?
for(customer in customers){
stripe.charges.create({
amount: 2000,
currency: "usd",
source: token,
customer: stripe_customerId,
}, {
idempotency_key: uuid
}, function(err, charge) {
// asynchronously called
});
}
Any ideas on this, please?
Share Improve this question edited May 28, 2018 at 17:55 Hopez asked May 28, 2018 at 17:20 HopezHopez 1411 silver badge9 bronze badges1 Answer
Reset to default 6First, you probably don't want to do a for
loop for asynchronous code like this; if you have n
Customers to charge, you'll make n
simultaneous requests, and that could cause a whole range of problems.
Second, you're using Charge code meant to create a one-off Charge from a Stripe Token, not create a Charge from a Customer.
Assuming you actually have saved Customer IDs, you'll probably want to look at using something like async for this.
I would approach it using #queue
, and I'd split things up as follows:
Iterate over the Customers, and for each, create a 'task' that includes the
customer
ID, theamount
, thecurrency
, a newly-generatedidempotency_key
, and anattempt_count
, and then push that task onto the queue;in the Queue 'processing' function, I would try creating a Charge with that task and its data, and if it fails due to a networking or other retryable error, I would increment
attempt_count
and push it back onto the queue so it can be retried. I'd probably also have a test to limit the number of retries, and skip/log any that failed, i.e. 5 times.