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

使用UnityWebRequest调用Twilio API报错:需提供'To'电话号码

Twilio API 21604错误排查与修复

问题背景

已通过Twilio官网API测试号码有效性,账号SID、Auth Token无问题,且验证了个人号码为Caller ID,但在Unity中调用API时,传入合法格式的recipientPhoneNumber仍返回错误:

Twilio API Response Text: {"code": 21604, "message": "A 'To' phone number is required.", "more_info": "https://www.twilio.com/docs/errors/21604", "status": 400}
Twilio API request error: HTTP/1.1 400 Bad Request

代码错误修复

核心问题是UnityWebRequest.Post的默认表单处理逻辑覆盖了JSON配置,导致Twilio服务器无法解析to字段:

错误原因

UnityWebRequest.Post(string uri, string postData)默认将传入的字符串当作表单数据处理,自动设置Content-Type为application/x-www-form-urlencoded,即使手动设置application/json也会被覆盖,最终JSON结构的参数无法被Twilio识别。

修正后的代码

public IEnumerator SendMessage(string recipientPhoneNumber, string message)
{
    Debug.Log("The recipient phone number is: " + recipientPhoneNumber);
    
    // 构造JSON请求体
    string jsonPayload = JsonUtility.ToJson(new
    {
        from = twilioPhoneNumber,
        to = recipientPhoneNumber,
        body = message
    });

    // 直接创建POST请求,避免默认表单处理
    UnityWebRequest request = new UnityWebRequest(twilioMessagesApiUrlFormatted, "POST");
    
    // 设置Basic Auth头
    string auth = accountSid + ":" + authToken;
    string base64Auth = System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(auth));
    request.SetRequestHeader("Authorization", "Basic " + base64Auth);
    
    // 明确指定Content-Type为JSON
    request.SetRequestHeader("Content-Type", "application/json");

    // 配置上传处理器,传入JSON字节数组
    byte[] jsonBytes = System.Text.Encoding.UTF8.GetBytes(jsonPayload);
    request.uploadHandler = new UploadHandlerRaw(jsonBytes);
    request.downloadHandler = new DownloadHandlerBuffer();

    // 发送请求
    yield return request.SendWebRequest();

    // 新增结果处理,便于调试
    if (request.result != UnityWebRequest.Result.Success)
    {
        Debug.LogError("Twilio API Error: " + request.error);
        Debug.LogError("Response: " + request.downloadHandler.text);
    }
    else
    {
        Debug.Log("Message sent successfully!");
        Debug.Log("Response: " + request.downloadHandler.text);
    }
}

额外检查项

  • 打印验证请求体:在代码中添加Debug.Log("JSON Payload: " + jsonPayload),确认to字段格式为+[国家代码][纯数字号码](如+1234567890)
  • API地址正确性:确认twilioMessagesApiUrlFormatted格式为https://api.twilio.com/2010-04-01/Accounts/{你的AccountSID}/Messages.json
  • 账号权限限制:试用账号仅能发送短信到已验证的Caller ID号码,无法发送到任意未验证号码;正式账号无此限制
  • Twilio号码功能:确认使用的Twilio号码支持短信发送(部分号码仅支持语音)

内容的提问来源于stack exchange,提问作者JM Wesierski

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 22:38:29