Home > other >  How to create a customer if it does not exist with payment intent API stripe PHP
How to create a customer if it does not exist with payment intent API stripe PHP

Time:11-27

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.
\Stripe\Stripe::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 = \Stripe\Customer::search([
        "query" => 'email:\'.'.$user['email'].'.\'', 
    ]);
    
    if ($query->id) {
        $customer_ID = $query->id;
    } else {
        $customer = \Stripe\Customer::create([
            "email" => $user["email"],
            "description" => 'VIP plan',
        ]);
        
        $customer_ID = $customer->id;
    }



    // Create a PaymentIntent with amount and currency
    $paymentIntent = \Stripe\PaymentIntent::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()]);
}

CodePudding user response:

Your search query is not a simple object but a multidimentional object.

'data' is missing on your object request :

$query->data[0]->id

You can't have access to datas so you might use a for loop as :

if(sizeof($query->data) !== 0)
{
   for($i=0;$i<sizeof($query->data);$i  )
   {
      $customer_ID = $query->data[$i]->id;
   }
}
else
{
   // Create customer
}

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 :

$query = \Stripe\Customer::search([
    "query" => 'email:\'.'.$user['email'].'.\'', 
    "limit" => 1,
]);

if(sizeof($query->data) !== 0)
{
   $customer_ID = $query->data[0]->id;
}
else
{
   // create customer
}
  • Related