How to retrieve the identifier of an existing customer via his email address or create the customer if he does not hesitate when creating a payment with API Stripe?
I searched in the Stripe documentation but couldn’t find the answer.
require "Stripe/vendor/autoload.php";
// This is your test secret API key.
StripeStripe::setApiKey("sk_test_XXX");
header("Content-Type: application/json");
try {
// retrieve JSON from POST body
$jsonStr = file_get_contents("php://input");
$jsonObj = json_decode($jsonStr);
// get customer if exist
$query = StripeCustomer::search([
"query" => 'email:'.'.$user['email'].'.'',
]);
if ($query->id) {
$customer_ID = $query->id;
} else {
$customer = StripeCustomer::create([
"email" => $user["email"],
"description" => 'VIP plan',
]);
$customer_ID = $customer->id;
}
// Create a PaymentIntent with amount and currency
$paymentIntent = StripePaymentIntent::create([
"customer" => $customer_ID,
"amount" => 1400,
"currency" => "usd",
"automatic_payment_methods" => [
"enabled" => true,
],
]);
$output = [
"clientSecret" => $paymentIntent->client_secret,
];
echo json_encode($output);
} catch (Error $e) {
http_response_code(500);
echo json_encode(["error" => $e->getMessage()]);
}
2
Answers
Query fields for customers source: https://stripe.com/docs/search#query-fields-for-customers
Here is the properly formatted query.
Your search query is not a simple object but a multidimentional object.
‘data’ is missing on your object request :
You can’t have access to datas so you might use a for loop as :
If you’re sure to have only one customer, you need to add a limit to the Stripe search query and so, you’ll don’t need to have for loop :