You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不存入数据库,保存API返回的OTP并复用至其他API?

问题分析与修复方案

你代码里的核心错误:

  • API响应的验证码字段是OPT(注意拼写),不是你写的OTP
  • 你直接从原始字符串$curl_response调用对象属性,这是错误的,必须使用JSON解码后的$response_data对象
  • 注释里的$user_data是无效变量,和实际定义的$response_data不匹配

修正后的OTP提取代码

$curl_response = curl_exec($curl);

// 先检查curl请求是否成功
if($curl_response === false) {
    die('Curl请求失败: ' . curl_error($curl));
}

// 解码JSON响应为PHP对象
$response_data = json_decode($curl_response);

// 检查JSON解码是否成功
if($response_data === null) {
    die('JSON解码失败: ' . json_last_error_msg());
}

// 提取OPT(注意字段名是OPT)
$otp = $response_data->OPT;
echo "OTP: " . $otp;

复用OTP到另一API调用

拿到$otp后,直接在新的Curl请求中传入即可,示例代码:

// 初始化第二个API的Curl请求
$second_curl = curl_init('https://your-second-api-endpoint.com');

// 构造包含OTP的请求参数
$post_params = [
    'MSISDN' => $response_data->MSISDN,
    'OTP' => $otp, // 这里根据第二个API的字段要求调整,可能是OPT或OTP
    // 其他必填参数
];

// 设置Curl选项
curl_setopt($second_curl, CURLOPT_POST, true);
curl_setopt($second_curl, CURLOPT_POSTFIELDS, http_build_query($post_params));
curl_setopt($second_curl, CURLOPT_RETURNTRANSFER, true);

// 执行请求并获取响应
$second_api_response = curl_exec($second_curl);
curl_close($second_curl);

// 处理第二个API的响应
var_dump($second_api_response);

额外提醒

  • 务必确保第一个Curl请求开启了CURLOPT_RETURNTRANSFER选项,否则curl_exec会直接输出响应内容,导致无法正常解码JSON
  • 保留错误处理逻辑,能快速排查请求或解码过程中出现的问题

内容的提问来源于stack exchange,提问作者Villaro 24

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 12:01:07