如何通过邮箱查询Stripe客户或创建新客户并生成Payment Intent(PHP)
解决Stripe通过邮箱查询/创建客户并关联Payment Intent的问题
问题分析
你需要实现的逻辑是通过客户邮箱查询已有客户ID,不存在则创建新客户,最后将客户关联到Payment Intent,现有代码存在几个关键问题:
Customer::search的查询语法错误,且对返回结果的判断逻辑不符合Stripe API规范- 未正确获取请求中的邮箱参数(
$user变量未定义) - 错误地直接访问搜索结果的
id属性,忽略了API返回的结构
修正后的完整代码
require "Stripe/vendor/autoload.php"; // 设置测试密钥 \Stripe\Stripe::setApiKey("sk_test_XXX"); header("Content-Type: application/json"); try { // 读取POST请求的JSON数据 $jsonStr = file_get_contents("php://input"); $jsonObj = json_decode($jsonStr); // 校验邮箱参数是否存在 if (empty($jsonObj->email)) { throw new Exception("客户邮箱不能为空"); } $customerEmail = $jsonObj->email; // 通过邮箱精确搜索客户,限制只返回1条结果 $searchResult = \Stripe\Customer::search([ "query" => "email:'{$customerEmail}'", "limit" => 1 ]); $customerId = null; // 检查搜索结果中是否存在匹配的客户 if (!empty($searchResult->data) && count($searchResult->data) > 0) { $customerId = $searchResult->data[0]->id; } else { // 创建新客户 $customer = \Stripe\Customer::create([ "email" => $customerEmail, "description" => 'VIP plan', ]); $customerId = $customer->id; } // 创建关联客户的Payment Intent $paymentIntent = \Stripe\PaymentIntent::create([ "customer" => $customerId, "amount" => 1400, "currency" => "usd", "automatic_payment_methods" => [ "enabled" => true, ], ]); echo json_encode([ "clientSecret" => $paymentIntent->client_secret, "customerId" => $customerId ]); } catch (\Exception $e) { http_response_code(500); echo json_encode(["error" => $e->getMessage()]); }
关键修正点说明
- 搜索逻辑修正:
- Stripe搜索API中,邮箱需用单引号包裹,正确格式为
"query" => "email:'{$customerEmail}'" search接口返回的是SearchResult对象,客户数据存储在data数组中,需通过$searchResult->data[0]获取首个匹配客户
- Stripe搜索API中,邮箱需用单引号包裹,正确格式为
- 参数校验:增加邮箱非空校验,避免空值触发API错误
- 变量修正:从请求的JSON对象中正确提取邮箱参数,替换未定义的
$user变量 - 异常处理:将
Error改为\Exception,覆盖更多业务逻辑异常场景
额外注意事项
- Stripe允许同一邮箱存在多个客户,若你的业务要求邮箱唯一,可在创建前增加更严格的判断逻辑
- 生产环境请替换为正式API密钥,并加强请求数据的合法性校验
内容的提问来源于stack exchange,提问作者Mary
相关产品推荐
相关产品推荐

