Can you pass a shipping address to Stripe Checkout in PHP?

2.6k views Asked by At

I'm using Stripe Checkout API to direct a website user to make payment.

Is there a way to pass a shipping address to the hosted checkout page so it's gathered from the referrer rather then Stripe themselves?

function createSession()
{
    require 'vendor/autoload.php';
    \Stripe\Stripe::setApiKey('[API_KEY_REDACTED]');
    
    $YOUR_DOMAIN = '[SITE_URL_REDACTED]';
    
    // Calculate price
    $price = 50;
    
    $checkout_session = \Stripe\Checkout\Session::create([
        'billing_address_collection' => 'required',
        'payment_method_types' => ['card'],
        'line_items' => [[
            'price_data' => [
                'currency' => 'gbp',
                'unit_amount' => $price,
                'product_data' => [
                    'name' => 'Product'
                ],
            ],
            'quantity' => 1,
        ]],
        'mode' => 'payment',
        'success_url' => $YOUR_DOMAIN . '/success',
        'cancel_url' => $YOUR_DOMAIN . '/cancel',
    ]);
    
    return json_encode(['id' => $checkout_session->id]);
}

You can add the following line to make Stripe ask for a shipping address, but I want to pass this from the referrer instead.

'shipping_address_collection' => [
    'allowed_countries' => ['US', 'CA'],
],
2

There are 2 answers

2
Nolan H On BEST ANSWER

To do this you would create a Customer and provide their shipping address, then provide that existing Customer when creating the Checkout session:

$checkout_session = \Stripe\Checkout\Session::create([
    'customer' => 'cus_123',
    ...
]);
0
Super Kai - Kazuya Ito On

You can use shipping_address_collection as shown below:

$checkout_session = \Stripe\Checkout\Session::create([
  ...
  'shipping_address_collection' => [
    'allowed_countries' => ['US', 'CA'],
  ],
  ...
]);

Also, you can use payment_intent_data.shipping to pass a shipping address to Shipping section in Payments on Stripe Dashboard as shown below. *This doesn't pass a shipping address to Stripe Checkout but does pass to Shipping section in Payments on Stripe Dashboard and you cannot use both shipping_address_collection and payment_intent_data.shipping at the same time otherwise there is an error:

$checkout_session = \Stripe\Checkout\Session::create([
  ...
  'payment_intent_data' => [
    'shipping' => [
      'name' => 'John Smith',
      'address' => [
        'country' => 'USA',
        'state' => 'California',
        'city' => 'San Francisco',
        'line1' => '58 Middle Point Rd',
        'line2' => '',
        'postal_code' => '94124'
      ]
    ]
  ],
  /*
  'shipping_address_collection' => [
    'allowed_countries' => ['US', 'CA'],
  ],
  */
  ...
]);

enter image description here