I am using Stripe elements to make an asychronous paymentRequest to charge customers. The request returns 'success' irrespective of the charge result so what's the best way to return a state so I can handle the charge state client side and report a failed charge? Do I need to use endpoints? Stripe seems to leave us hanging after the charge with no guidance.
Listener:
<script>
paymentRequest.on('token', function(ev) {
fetch('https://example.com/pub/apple.php', {
method: 'POST',
body: JSON.stringify({token: ev.token.id , email: ev.token.email}),
headers: {'content-type': 'application/json'},
})
.then(function(response) {
if (response.ok) {
// Report to the browser that the payment was successful, prompting
// it to close the browser payment interface.
ev.complete('success');
} else {
// Report to the browser that the payment failed, prompting it to
// re-show the payment interface, or show an error message and close
// the payment interface.
ev.complete('fail');
}
});
});
</script>
https://example.com/pub/apple.php:
require_once('../_stripe-php-4.9.0/init.php');
// Retrieve the request's body and parse it as JSON
$input = @file_get_contents("php://input");
$json = json_decode($input);
// get the token from the returned object
$token = $json->token;
$email = $json->email;
$skey = 'sk_test_Y********************F';
\Stripe\Stripe::setApiKey($skey);
// create the customer
$customer = \Stripe\Customer::create(array(
"source" => $token,
"description" => 'Device',
"email" => $email)
);
//charge the card
$charge = \Stripe\Charge::create(array(
"amount" => 1000,
"currency" => 'GBP',
"statement_descriptor" => 'MTL',
"description" => 'Device - '.$customer->id,
"customer" => $customer->id)
);