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

寻求Twilio /Message资源的C++实现示例及迁移方案

迁移至Twilio Messages Resource URI的C++实现示例

依赖准备

确保项目已集成以下工具/库:

  • libcurl:用于发送HTTP请求
  • nlohmann/json(可选但推荐):用于解析Twilio返回的JSON响应

完整示例代码

以下是调用Messages Resource API发送消息、处理响应并记录事件的实现:

#include <iostream>
#include <string>
#include <curl/curl.h>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

// 回调函数:接收HTTP响应内容
size_t WriteCallback(void *contents, size_t size, size_t nmemb, std::string *s) {
    size_t newLength = size * nmemb;
    try {
        s->append((char*)contents, newLength);
    } catch(std::bad_alloc &e) {
        return 0;
    }
    return newLength;
}

// 发送Twilio消息并记录事件
bool SendTwilioMessageAndLog(const std::string& accountSid, const std::string& authToken,
                             const std::string& fromNumber, const std::string& toNumber,
                             const std::string& messageBody) {
    CURL *curl;
    CURLcode res;
    std::string readBuffer;
    std::string auth = accountSid + ":" + authToken;

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if(curl) {
        // 设置API端点
        std::string url = "https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/Messages.json";
        
        // 构造POST参数(URL编码)
        char* encodedFrom = curl_easy_escape(curl, fromNumber.c_str(), fromNumber.length());
        char* encodedTo = curl_easy_escape(curl, toNumber.c_str(), toNumber.length());
        char* encodedBody = curl_easy_escape(curl, messageBody.c_str(), messageBody.length());
        
        std::string postFields = "From=" + std::string(encodedFrom) +
                                 "&To=" + std::string(encodedTo) +
                                 "&Body=" + std::string(encodedBody);

        // 释放编码后的临时内存
        curl_free(encodedFrom);
        curl_free(encodedTo);
        curl_free(encodedBody);

        // 设置curl核心选项
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postFields.c_str());
        curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_easy_setopt(curl, CURLOPT_USERPWD, auth.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);

        // 执行请求
        res = curl_easy_perform(curl);
        
        // 处理响应与事件记录
        if(res != CURLE_OK) {
            fprintf(stderr, "curl请求失败: %s\n", curl_easy_strerror(res));
            std::cout << "[事件记录] 消息发送失败:网络请求错误 - " << curl_easy_strerror(res) << std::endl;
        } else {
            long responseCode;
            curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responseCode);
            
            if(responseCode == 201) {
                json responseJson = json::parse(readBuffer);
                std::string messageSid = responseJson["sid"];
                std::string status = responseJson["status"];
                std::cout << "[事件记录] 消息发送成功,MessageSid:" << messageSid << ",当前状态:" << status << std::endl;
            } else {
                json errorJson = json::parse(readBuffer);
                std::string errorCode = errorJson["code"];
                std::string errorMsg = errorJson["message"];
                std::cout << "[事件记录] 消息发送失败,响应码:" << responseCode << ",错误码:" << errorCode << ",错误信息:" << errorMsg << std::endl;
            }
        }

        // 清理curl资源
        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();

    return (res == CURLE_OK);
}

// 调用示例
int main() {
    // 替换为你的Twilio账号信息
    std::string accountSid = "YOUR_ACCOUNT_SID";
    std::string authToken = "YOUR_AUTH_TOKEN";
    std::string fromNumber = "+1234567890";
    std::string toNumber = "+0987654321";
    std::string messageBody = "测试:已迁移至Messages Resource URI";

    SendTwilioMessageAndLog(accountSid, authToken, fromNumber, toNumber, messageBody);
    return 0;
}

迁移关键要点

  • 接口路径替换:将旧Rest接口替换为标准Messages Resource URI:/2010-04-01/Accounts/{AccountSid}/Messages.json
  • 认证逻辑:保持Basic Auth机制,用AccountSid和AuthToken作为用户名/密码
  • 参数规范:使用Twilio官方要求的参数(From/To/Body等),必须对参数做URL编码避免格式错误
  • 响应判断:以HTTP 201作为请求成功标志,解析JSON响应提取sid/status等字段用于事件记录
  • 错误处理:区分curl网络错误和Twilio业务错误,分别记录对应事件信息

编译说明

使用g编译时需链接libcurl并指定C版本:

g++ -std=c++17 twilio_messages.cpp -o twilio_messages -lcurl

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 01:55:34