byronyasgur
byronyasgur

Reputation: 4737

How can I adapt this Stripe checkout code to work with cents as well as dollars?

I am working on this code which is from the Stripe website

URL : https://stripe.com/docs/checkout/integration-builder

this is directly from the website and works fine for me

$checkout_session = \Stripe\Checkout\Session::create([
  'payment_method_types' => ['card'],
  'line_items' => [[
    'price_data' => [
      'currency' => 'usd',
      'unit_amount' => 2000,
      'product_data' => [
        'name' => 'Stubborn Attachments',
        'images' => ["https://i.imgur.com/EHyR2nP.png"],
      ],
    ],
    'quantity' => 1,
  ]],
  'mode' => 'payment',
  'success_url' => $YOUR_DOMAIN . '/success.html',
  'cancel_url' => $YOUR_DOMAIN . '/cancel.html',
]);

However when I change the code to the below to try to get the dollar and cents working ( using either unit_amount as in the example ... or unit_amount_decimal as suggested by this page https://stripe.com/docs/billing/subscriptions/decimal-amounts ) then there are issues which I dont really understand, particularly the error returned when using unit_amount_decimal because it appears that there's no way to do decimal places in Stripe ... which hopefully is not the case.

How would I do this if not as they suggest on that page ... which seems to not work?

same code with 2000.55 instead of 2000

$checkout_session = \Stripe\Checkout\Session::create([
  'payment_method_types' => ['card'],
  'line_items' => [[
    'price_data' => [
      'currency' => 'usd',
      'unit_amount_decimal' => 2000.55,
      'product_data' => [
        'name' => 'Stubborn Attachments',
        'images' => ["https://i.imgur.com/EHyR2nP.png"],
      ],
    ],
    'quantity' => 1,
  ]],
  'mode' => 'payment',
  'success_url' => $YOUR_DOMAIN . '/success.html',
  'cancel_url' => $YOUR_DOMAIN . '/cancel.html',
]);

network tab errors

using unit_amount Invalid integer: 2000.55

using unit_amount_decimal Checkout does not currently support usd prices with more than 2 decimal places in line_items[0]. You passed 2000.55 corresponding to $20.0055, which is not supported.

The second error seems to be suggesting that this is not possible, yet this makes no sense since products are not always even dollar amounts.

Upvotes: 0

Views: 1493

Answers (1)

Rory
Rory

Reputation: 2496

Stripe measures amounts in the smallest unit of a currency - for example cents for USD:

'unit_amount' => 2000, //2000 cents or $20

'unit_amount' => 2050, //2050 cents or $20.50

If you need to use a decimal amount of the smallest unit - e.g. 1.5 cents per action then use 'unit_amount_decimal'

'unit_amount_decimal' => 1.5 // 1.5¢ or $0.015 per action

Upvotes: 1

Related Questions