I'm using Stripe Checkout to create a payment form on my website that needs to use 3 separate Stripe accounts, based on a dropdown selection in a single form.
On the HTML/JS side, I've successfully been able to dynamically set the public key for the Stripe payment.
On the PHP side of things, I want to set the secret key depending on the public key that is submitted.
Aside from the obvious question of whether it's safe to do so, what would that PHP code look like?
This is my reference at the moment: https://stripe.com/docs/checkout/php
Below is what I had in mind for the PHP code. Also appreciate better solutions if my intuition is off.
<?php
require_once('vendor/autoload.php');
$stripeStore1 = array(
"secret_key" => "...",
"publishable_key" => "..."
);
$stripeStore2 = array(
"secret_key" => "...",
"publishable_key" => "..."
);
$stripeStore3 = array(
"secret_key" => "...",
"publishable_key" => "..."
);
// if form name='key' == a
\Stripe\Stripe::setApiKey($stripeStore1['secret_key']);
// if form name='key' == b
\Stripe\Stripe::setApiKey($stripeStore2['secret_key']);
// if form name='key' == c
\Stripe\Stripe::setApiKey($stripeStore3['secret_key']);
?>
Here's how my JS code looks.
$('#customButton').on('click', function(e) {
// Open Checkout with further options
if (validateForm()) {
var store = selectStore();
var handler = StripeCheckout.configure({
key: store.testKey, // toggle Stripe mode here
name: store.name,
panelLabel: 'Pay {{amount}}',
token: function(token) {
// Use the token to create the charge with a server-side script.
// You can access the token ID with `token.id`
}
});
handler.open({
zipCode: true,
amount: 1500
});
}
e.preventDefault();
});
Your intuition looks pretty much right to me.
Since it looks like you're using Checkout (which takes care of submitting the card number on the client side using stripe.js, and then gives you a token to use instead in your code), your Javascript needs to change the public key to the one corresponding to the appropriate account. After the token is generated (and returned from stripe.js to your code), you pass this over to your PHP script, along with something to identify which Stripe account you used, and then the PHP script does the actual charge using the appropriate secret key on the backend.
I would add something in there to handle an invalid identifier coming from your Javascript, but ultimately (from what I understand of stripe.js) the token can only correspond to one account. If $_POST['key']
= a
and you can't find the token using the secret key for the "a" account, make sure you handle that appropriately.