Dox
Dox

Reputation: 591

Stripe: attribute charge with single use token to customer

I'm pretty sure this is a basic question, but I couldn't find the answer in the docs or on google.

I am trying to attribute a charge to a customer. So, I am creating a single-use token to charge a card, but I am trying to figure out how to connect that charge to a customer that I've already created. Let's say the customer doesn't want to use their previously stored credit card. Here's what I tried to do, but it is returning an error because Stripe thinks I am trying to charge the customer and the card (which is probably what I'm telling it to do, here).

$charge = \Stripe\Charge::create(array(
  "amount" => $product_price, // amount in cents, again
  "currency" => "usd",
  "customer" => $customer_id,
  "source" => $token,
  "description" => "Example charge"
));

How would someone attach a single-use token charge to a customer?

Upvotes: 0

Views: 685

Answers (2)

mckelvaney
mckelvaney

Reputation: 1

For anyone finding this many years later via search

A single-use charge can be made via Stripe and attributed to a Customer without saving that card as a reusable source on the Customer - https://stripe.com/docs/stripe-js/reference#stripe-create-source.

It is achieved by using the Source API in Stripe.js or Elements, that is, by creating a "standalone" source, not a card token - https://stripe.com/docs/stripe-js/reference#stripe-create-source

When tokenizing a card, that is a reusable source that must be attached to a customer, when creating a source, that can be used for a single-use charge, you can optionally attach it to a customer for internal tracking. This source can not be used again for any future transactions.

Use the stripe.createSource from the Stripe.js or Elements and then pass the id of the returned object (source.id) to your backend, you can then use this to create a charge associated with a Customer.

PHP:

$charge = \Stripe\Charge::create([
  'amount' => 1099,
  'currency' => 'eur',
  'customer' => 'cus_AFGbOSiITuJVDs',
  'source' => 'src_18eYalAHEMiOZZp1l9ZTjSU0',
]);

Ruby:

charge = Stripe::Charge.create({
  amount: 1099,
  currency: 'eur',
  customer: 'cus_AFGbOSiITuJVDs',
  source: 'src_18eYalAHEMiOZZp1l9ZTjSU0',
})

Upvotes: 0

Adamjstevenson
Adamjstevenson

Reputation: 435

You won't be able to attribute an already created charge to a customer after the charge has been created. Likewise, once a token's been used for a charge you won't be able to use it again. Instead, you'd need to create a customer object, attach that unused token as the source, then create the charge by passing the customer parameter. There's an example of all of this here: https://stripe.com/docs/charges#saving-credit-card-details-for-later

Upvotes: 1

Related Questions