问题
I have integrated Stripe into my site. The code below is copied directly from stripe's documentation. Although there are minor differences between this code and my implementation, such differences are not relevant to the question as both my code and the code is shown work correctly
First I install relevant files.
composer.json
{
"require": {
"stripe/stripe-php": "*"
}
}
Then I make a checkout in JavaScript. (This one charges $9.99 for "Example Charge" but you get the idea. Below is a simple checkout, mine is a custom checkout, but that should not make a difference to the question.)
<form action="nextpage.php" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<test key here>"
data-amount="999"
data-name="<myName>"
data-description="Example charge"
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="auto"
data-currency="aud">
</script>
</form>
This checkout is pretty good at catching most errors, and if it can't find any, it passes a token on for me to charge.
Finally, I added a page to create the charge
require 'vendor/autoload.php';
\Stripe\Stripe::setApiKey("<test key here>");
$token = $_POST['stripeToken'];
$charge = \Stripe\Charge::create([
'amount' => 999,
'currency' => 'aud',
'description' => 'Example charge',
'source' => $token,
]);
So far it is good. In the testing environment, this always succeeds. Or, if I test a card that should not succeed, it always fails at the checkout.
However, suppose the token is created successfully, but then the issue happens server side. How do I detect that?
More specifically, if I were to have a function like alert("Your payment has been successful")
or echo "Your payment has been successful"
, Where would be the correct place to call that from?
回答1:
Just figured it out shortly after posting.
First I noticed that $charge
is an output in this context, so I ran echo var_dump($charge);
which opened up a massive wealth of information.
Rather than look at it there, I can find the api reference here, scroll down to "The Charge Object". Within that, status
(relating to $charge['status']
) can confirm if it was successful or not.
The working code if($charge['status'] === "succeeded"){}
is the correct place to put a success message.
回答2:
try{
require 'vendor/autoload.php';
\Stripe\Stripe::setApiKey("<test key here>");
$token = $_POST['stripeToken'];
$charge = \Stripe\Charge::create([
'amount' => 999,
'currency' => 'aud',
'description' => 'Example charge',
'source' => $token,
]);
if(isset($charge->id) && $charge->id != ''){
echo "Payment has been made successful, Transaction ID : ".$charge->id;exit;
}
} catch (\Stripe\Error\Base $e) {
echo "Something went wrong with payment, Note : ".$e->getMessage();exit;
}
来源:https://stackoverflow.com/questions/52158321/where-do-i-call-the-payment-was-successful-message-from