最近业务上需要实现短信验证码的发送,搜索了几家进了对比,最终选择腾讯云的,下面开始进入正题
环境Ubuntu18,语言C++
1、下载skd源码
下载官方提供的C++接口源码。github下载地址:https://github.com/tencentcloud/tencentcloud-sdk-cpp
2、编译修改cmake文件,编译源码
下载完成后只留core和sms目录,其余的删除。如图:
修改CMakeList.txt文件,保留add_subdirectory(core)、add_subdirectory(sms)这两行,其余删除,如图:
3、安装依赖环境
编译器
- 安装支持 C++ 11 或更高版本的编译器:GCC 4.8 或以上版本
- 暂时仅支持 Linux 环境,不支持 Windows 环境
编译工具
安装 cmake 3.0 或以上版本,例如:
ubuntu
sudo apt-get install cmake
centos
yum install cmake3
依赖库
安装例子如下:
ubuntu
sudo apt-get install libcurl4-openssl-dev
centos
yum install libcurl-devel
备注:建议安装最新版的 libcurl 库,否则可能存在 libcurl 库内存泄露 bug 问题。
安装例子如下:
ubuntu
sudo apt-get install libssl-dev
centos
yum install openssl-devel
- libuuid
安装例子如下:
ubuntu
sudo apt-get install uuid-dev
centos
yum install libuuid-devel
从源代码构建 SDK
-
前往 Github 代码托管地址 下载最新代码
-
进入 SDK 创建生成必要的构建文件
cd <path/to/tencentcloud-sdk-cpp>
mkdir sdk_build
cd sdk_build
cmake ..
make
sudo make install
ubuntu
sudo apt-get install cmake
centos
yum install cmake3
4、测试代码
#include <iostream>
#include <tencentcloud/core/TencentCloud.h>
#include <tencentcloud/core/Credential.h>
#include <tencentcloud/sms/v20190711/SmsClient.h>
#include <string>
#include <vector>
using namespace TencentCloud;
using namespace TencentCloud::Sms::V20190711;
using namespace TencentCloud::Sms::V20190711::Model;
using namespace std;
int main()
{
// 必须调用初始化函数
//TencentCloud::InitAPI();
string secretId = "填写自己的secretId";
string secretKey = "填写自己的secretKey";
Credential cred = Credential(secretId, secretKey);
ClientProfile clientProfile;
HttpProfile httpProfile;
httpProfile.SetEndpoint("sms.tencentcloudapi.com");
clientProfile.SetHttpProfile(httpProfile);
SmsClient client(cred, "ap-beijing", clientProfile);
SendSmsRequest req;
//设置手机号
std::vector<std::string> phoneNumbers;
phoneNumbers.push_back("+86填写要发送的手机号");
req.SetPhoneNumberSet(phoneNumbers);
//设置模板id
req.SetTemplateID("填写自己的模板Id");
//设置短信SdkAppid
req.SetSmsSdkAppid("填写自己的SdkAppId");
//设置签名内容
req.SetSign("填写自己的签名内容");
//设置模板参数
std::vector<std::string> templateParam;
templateParam.push_back("发送的验证码");
templateParam.push_back("验证码有效时间");
req.SetTemplateParamSet(templateParam);
SmsClient::SendSmsOutcome out = client.SendSms(req);
Error err = out.GetError();
cout << "err.GetErrorMessage:" << err.GetErrorMessage() << endl;
cout << "err.GetErrorCode:" << err.GetErrorCode() << endl;
SendSmsResponse res = out.GetResult();
std::vector<SendStatus> status = res.GetSendStatusSet();
for (auto item : status) {
cout << "item.GetSerialNo:" << item.GetSerialNo() << endl;
cout << "item.GetPhoneNumber:" << item.GetPhoneNumber() << endl;
cout << "item.GetFee:" << item.GetFee() << endl;
cout << "item.GetSessionContext:" << item.GetSessionContext() << endl;
cout << "item.GetCode:" << item.GetCode() << endl;
cout << "item.GetMessage:" << item.GetMessage() << endl;
cout << "item.GetIsoCode:" << item.GetIsoCode() << endl;
}
bool isok = out.IsSuccess();
cout << "isok:" << isok << endl;
return 0;
}
更多信息请加入c++技术群:690018451