Reputation: 117
I keep receiving a 400 error while creating a charge with Stripe. The strange thing is that sometimes it works fine but most of the time it doesn't work at all. The payments go through each time as well. Regardless of the error. Is this php script correct for processing payments?
Note: I've checked and each time I create a charge the token is unique from the last one.
<?php
require_once('stripe.php');
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
\Stripe\Stripe::setApiKey("key");
$token = $_POST['stripeToken'];
$email = $_POST['email'];
// Create the charge on Stripe's servers - this will charge the user's card
try {
// Create a Customer:
$customer = \Stripe\Customer::create(array(
"email" => $email,
"source" => $token,
));
// Charge the Customer instead of the card:
$charge = \Stripe\Charge::create(array(
"amount" => 1000,
"currency" => "usd",
"customer" => $customer->id
));
} catch(\Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card will be caught
$body = $e->getJsonBody();
$err = $body['error'];
print('Status is:' . $e->getHttpStatus() . "\n");
print('Type is:' . $err['type'] . "\n");
print('Code is:' . $err['code'] . "\n");
// param is '' in this case
print('Param is:' . $err['param'] . "\n");
print('Message is:' . $err['message'] . "\n");
} catch (\Stripe\Error\RateLimit $e) {
$response["error"] = TRUE;
$response["error_msg"] = "Error processing payment - Rate Limit.";
echo json_encode($response);
} catch (\Stripe\Error\InvalidRequest $e) {
$response["error"] = TRUE;
$response["error_msg"] = "Error processing payment - Invalid request.";
echo json_encode($response);
} catch (\Stripe\Error\Authentication $e) {
$response["error"] = TRUE;
$response["error_msg"] = "Error processing payment - Authentication.";
echo json_encode($response);
} catch (\Stripe\Error\ApiConnection $e) {
$response["error"] = TRUE;
$response["error_msg"] = "Error processing payment - API Connection.";
echo json_encode($response);
} catch (\Stripe\Error\Base $e) {
$response["error"] = TRUE;
$response["error_msg"] = "Error processing payment - Base.";
echo json_encode($response);
} catch (Exception $e) {
$response["error"] = TRUE;
$response["error_msg"] = "Error processing payment - Exception.";
echo json_encode($response);
}
?>
Upvotes: 1
Views: 3648
Reputation: 27
You are using the token twice. Once for the charge and the other to create the customer. You don't have to use a token to create a customer.
$customer = \Stripe\Customer::create(array(
"email" => $email,
// "source" => $token, //remove
));
Upvotes: 2
Reputation: 8727
The most likely cause is that the Token is being POSTed more than once from your client-side code - either because the customer is clicking more than once, or because the code is causing the data to be submitted more than once.
Upvotes: 1