如何创建一个客户,如果它不存在与付款意向API条带PHP

zwghvu4y  于 2022-11-28  发布在  PHP
关注(0)|答案(1)|浏览(136)

如何通过现有客户的电子邮件地址检索其标识符,或者如果客户在使用API Stripe创建付款时毫不犹豫地创建客户?
我在Stripe文档中进行了搜索,但没有找到答案。

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()]);
}
qij5mzcb

qij5mzcb1#

您的搜索查询不是一个简单的对象,而是一个多维对象。
您的对象请求中缺少“data”:

$query->data[0]->id

你不能访问数据,所以你可以使用for循环:

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

如果您确定只有一个客户,则需要为Stripe搜索查询添加一个限制,这样就不需要for循环:

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

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

相关问题