Reputation: 89
I am trying to integrate Stripe in a php project and all is working fine except the fact that the payment intent client_secret is always null and I actually know why but couldn't figure how to fix it, I am using a javascript file in which there is a listener for the submit button for the payment intent creation. The problem is that the listener try to fetch the json data before its creation, the client_secret value is null because I am setting its value just after creating the payment intent, how could solve this? any advice could help, thanks.
Here is the code I wrote: intent.php:
$intent= \Stripe\PaymentIntent::create(
array(
'amount' => $price + ($price * $tva),
'currency' => 'EUR',
'setup_future_usage' => 'off_session',
)
);
$intentcls=$intent->client_secret;
intent.js:
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
var response = fetch('/secret').then(function(response) {
return response.json();
}).then(function(responseJson) {
var clientSecret = responseJson.client_secret;
stripe.confirmCardPayment(
clientSecret,
{
payment_method: {card: card}
}
).then(function(result) {
if (result.error) {
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
var errorElement = document.getElementById('card-errors');
errorElement.textContent = 'Paiement effectué avec succées';
stripeTokenHandler(result.token);
}
});
secret.php:
echo json_encode(array('clientsecret' => $intentcls));
Upvotes: 0
Views: 1693
Reputation: 5847
You'll need to rearrange your logic to ensure the PaymentIntent is created before (or during) your fetch request to the backend.
If you already know the amount, you could create the PaymentIntent on page load.
A better solution is to create it when the call to /secret
is made, then return the client_secret
after the creation call to the Stripe API is complete.
secret.php could be:
$intent = \Stripe\PaymentIntent::create(
array(
'amount' => $amount, // calculate amount before this block
'currency' => 'EUR',
'setup_future_usage' => 'off_session',
)
);
echo json_encode(array('client_secret' => $intent->client_secret));
// perhaps store the ID in your database here
Upvotes: 2