将PHP cURL POST请求转为Google Apps Script时遇500错误求排查
排查Google Apps Script调用VoIP.ms短信API返回500错误的问题
VoIP.ms提供可发送短信的API,给出了PHP cURL示例代码,用户通过终端curl命令可成功发送短信,但自行编写的Google Apps Script运行时返回500服务器错误,错误信息显示SOAP相关异常,现排查问题所在。
PHP示例代码
<? $postfields = array( 'api_username'=>'john@domain.com', 'api_password'=>'password', 'method'=>'getServersInfo', 'server_pop'=>'1' ); $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true ); curl_setopt($ch, CURLOPT_POST, true ); curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); curl_setopt($ch, CURLOPT_URL, "https://voip.ms/api/v1/rest.php"); $result = curl_exec($ch); curl_close($ch); $data=json_decode($result,true); echo "<pre>"; print_r($data); echo "</pre>"; ?>
可正常运行的终端curl命令
curl -X POST -F 'api_username=john@domain.com' -F 'api_password=password' -F 'method=sendSMS' -F 'did=1234567890' -F 'dst=0987654321' -F 'message=Hello' https://voip.ms/api/v1/rest.php
用户编写的Google Apps Script代码
function sendSMS() { var formData = { api_username : "john@domain.com", api_password : "password", method : "sendSMS", did : 1234567890, dst : 0987654321, message : "Hello" }; var options = { method : "POST", payload : formData }; UrlFetchApp.fetch("https://voip.ms/api/v1/rest.php", options); }
错误信息
Exception: Request failed for https://voip.ms returned code 500. Truncated server response:
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">env:Bodyenv:Faultenv:Codeenv:Value... (use muteHttpExceptions option to examine full response)
sendSMS @ Code.gs:14
问题原因及修复方案
核心问题
Google Apps Script的UrlFetchApp默认将对象格式的payload编码为application/x-www-form-urlencoded,但VoIP.ms API需要的是multipart/form-data格式(对应curl的-F参数、PHP传递数组给CURLOPT_POSTFIELDS的自动编码)。此外,dst字段的0987654321作为数字会丢失前导零,必须以字符串形式传递。
修复后的代码
function sendSMS() { var formData = { api_username: "john@domain.com", api_password: "password", method: "sendSMS", did: "1234567890", dst: "0987654321", message: "Hello" }; var options = { method: "POST", payload: formData, contentType: "multipart/form-data" }; // 开启异常静默并打印响应,方便调试 var response = UrlFetchApp.fetch("https://voip.ms/api/v1/rest.php", { ...options, muteHttpExceptions: true }); Logger.log(response.getContentText()); }
关键修改点
- 添加
contentType: "multipart/form-data",确保请求格式与curl/PHP示例一致 - 将
did和dst改为字符串类型,避免前导零丢失或数字格式解析错误 - 增加
muteHttpExceptions: true并打印响应内容,便于后续排查其他潜在问题
内容的提问来源于stack exchange,提问作者Pablo
相关产品推荐
相关产品推荐

