Laravel返回合并响应问题:短信接口结果为何混入自定义响应?
问题解答:Laravel中短信接口响应与自定义响应合并的原因及解决办法
问题现象
调用发送OTP短信的方法后,短信接口的响应内容被直接追加到自定义响应的开头,最终返回的响应是两个JSON字符串拼接在一起:
{"Value":"5589489218988866748","RetStatus":1,"StrRetStatus":"Ok"}{"result":"verificationCode has sent","message":"ok","status":"200"}
相关代码
主函数代码
$otp = rand(12345, 99999); VerificationCode::create([ 'mobile' => $mobile, 'otp' => $otp, 'expire_at' => Carbon::now()->addMinutes(10) ]); $this->sendSms($otp, $mobile); return response([ 'result' => 'verificationCode has sent', 'message' => 'ok', 'status' => '200' ]);
sendSms函数代码
public function sendSms($otp, $mobile){ $post_data = http_build_query($data); $handle = curl_init('https://example.com/api/SendSMS/BaseServiceNumber'); curl_setopt($handle, CURLOPT_HTTPHEADER, array( 'content-type' => 'application/x-www-form-urlencoded' )); // curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($handle, CURLOPT_POST, true); curl_setopt($handle, CURLOPT_POSTFIELDS, $post_data); curl_setopt($handle, CURLOPT_RETURNTRANSFER, false); $response = curl_exec($handle); curl_close($handle); return $response; }
原因分析
问题核心出在sendSms函数的curl参数设置:
CURLOPT_RETURNTRANSFER被设置为false(curl默认值),此时curl_exec()会直接将短信接口的响应内容输出到HTTP响应流中,而非把内容返回给$response变量。- 执行
$this->sendSms()时,短信接口的响应已经被输出到客户端;后续return response()又输出了自定义JSON响应,导致两个JSON字符串被直接拼接,出现响应合并的情况。
解决办法
修改sendSms函数中的CURLOPT_RETURNTRANSFER参数为true,让curl将响应内容返回给变量,而非直接输出:
public function sendSms($otp, $mobile){ // 补充定义$data变量,填充短信接口所需参数 $data = [ 'otp' => $otp, 'mobile' => $mobile // 其他短信接口必填参数 ]; $post_data = http_build_query($data); $handle = curl_init('https://example.com/api/SendSMS/BaseServiceNumber'); curl_setopt($handle, CURLOPT_HTTPHEADER, array( 'content-type' => 'application/x-www-form-urlencoded' )); curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); // 启用此参数 curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($handle, CURLOPT_POST, true); curl_setopt($handle, CURLOPT_POSTFIELDS, $post_data); $response = curl_exec($handle); curl_close($handle); // 可选:可在此处处理短信接口响应,比如校验发送状态 // $responseData = json_decode($response, true); return $response; }
注意:原代码中$data变量未定义,需补充短信接口所需参数,否则http_build_query会抛出错误。
内容的提问来源于stack exchange,提问作者Saeed Mi
相关产品推荐
相关产品推荐

