前言
近期做网页注册需要用到发送验证码功能,于是用荣联云的发送短信验证码进行测试,官网上提供的demo是python2.7的,而目前都使用的python3了,而且demo中的代码太长了,我只取demo中发送单条短信的部分进行修改,首先具体步骤如下:
登录官网 https://www.yuntongxun.com
1、注册账号(需要用到手机号)
2、查看开发文档,得到api接口参数
3、根据demo重新编写python代码
短信发送接口
1.1 业务流程说明
1.2 Base URL
模板短信API引用的地址有Base URL。
生产环境的Base URL:https://app.cloopen.com:8883
注意:为了确保数据隐私,云通讯平台的REST API是通过HTTPS方式请求。
1.3 统一请求包头
URL格式:/2013-12-26/Accounts/{accountSid}/SMS/TemplateSMS?sig={SigParameter}
在URL格式中 {}内的内容表示为参数,非{}的内容固定不变。
1.4 HTTP标准包头字段
Accept:application/xml;
Content-Type:application/xml;charset=utf-8;
Content-Length:256;
Authorization:
属性说明:
1.5 请求包体
根据官网上所提供的这些要求,我们就可以进行代码的编写了。
import datetime
import base64
import hashlib
import requests
import json
class RongLian(object):
def __init__(self):
self.AccountSid = '' # 填写首页上对应的AccountSid
self.AccountToken = '' # 填写首页上对应的AccountToken
self.AppId = '' # 填写首页上对应的AppId
self.ServerPort = '8883'
self.ServerIP = 'app.cloopen.com'
self.SoftVersion = '2013-12-26'
self.Batch = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
def send_template_sms(self, phone, data):
# 生成sig
signature = self.AccountSid + self.AccountToken + self.Batch
# MD5
sig = hashlib.md5(signature.encode('utf-8')).hexdigest().upper()
# 拼接URL
url = "https://" + self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/SMS/TemplateSMS?sig=" + sig
# 生成auth
src = self.AccountSid + ":" + self.Batch
auth = base64.encodebytes(bytes(src, 'utf-8')).strip()
# 创建包头
headers = {
"Accept": 'application/json',
'Content-Type': 'application/json;charset=utf-8',
"Authorization": auth,
}
# 创建包体
body = {
"to": "".join(phone),
"appId": self.AppId,
"templateId": "1", # 这里由于是测试,所以模板为1
"datas": data,
}
req = requests.post(url, headers=headers, json=body)
re_json = json.loads(req.text) # 最后返回的是json字典
print(re_json)
return re_json
然后我们就可以进行测试了,最后可以根据返回字典中的"statusCode"来判断是否成功,如果为"000000"则表示发送成功,否则就不成功,如果不成功,可以通过"statusMsg"来查看错误原因。
if __name__ == '__main__':
ronglian = RongLian()
ronglian.send_template_sms('13152654178', ('4753', '5'))
通过传递的列表中的两个参数,最后会收到如下短信
【云通讯】您使用的是云通讯短信模板,您的验证码是4753,请于5分钟内正确输入