使用Arkesel发送语音短信报错:缺少'contents'键求助
解决Arkesel语音短信接口报错"A 'contents' key is required"的问题
问题分析
你遇到的报错提示需要contents键,但Postman中仅上传voice_file和recipients[]就能正常请求,核心原因是Laravel Http客户端在发送带文件的请求时,未正确以multipart/form-data格式传递参数,导致接口无法识别你提交的recipients参数,进而误判缺少必填的contents字段。
解决方案
需要在请求中显式添加->asMultipart()方法,确保请求以multipart格式发送,同时确认recipients参数是数组格式(即使只有一个手机号)。
修改后的代码如下:
public function makeCall($recipients) { $filePath = storage_path('app/public/assets/harvard.wav'); // 检查文件是否存在 if (!file_exists($filePath)) { throw new Exception("音频文件不存在:{$filePath}"); } // 确保recipients是数组格式 if (!is_array($recipients)) { $recipients = [$recipients]; } try { $response = Http::withHeaders([ 'api-key' => $this->apiKey ]) ->asMultipart() // 显式声明为multipart请求 ->attach('voice_file', fopen($filePath, 'r'), 'harvard.wav') ->post('https://sms.arkesel.com/api/v2/sms/voice/send', [ 'recipients' => $recipients, ]); if ($response->successful()) { Log::info("语音短信发送成功:", ['recipients' => $recipients, 'response' => $response->json()]); return $response->json(); } else { Log::error("语音短信发送失败:", ['recipients' => $recipients, 'error' => $response->body()]); throw new Exception("Arkesel错误:" . $response->body()); } } catch (Exception $e) { Log::error("语音短信发送异常:", ['recipients' => $recipients, 'error' => $e->getMessage()]); throw new Exception("Arkesel错误:" . $e->getMessage()); } }
额外说明
->asMultipart()会强制Laravel以multipart/form-data编码发送请求,和你在Postman中使用的格式完全一致,接口就能正确识别voice_file和recipients参数。- 确保
$recipients是数组,即使只有一个手机号,这样Laravel会自动将其转换为recipients[]的表单字段,匹配接口的参数要求。
内容的提问来源于stack exchange,提问作者Mahfuz Abdallah
相关产品推荐
相关产品推荐

