1017短信验证
02_requests.py
"""
# @TIME: 2021/10/16 下午10:08
# @FILE: 02_requests.py
# @AUTHOR: HANG1720
# @COMMIT: 发送请求
"""
import requests
html = requests.get('http://www.jd.com')
print(html)
# 获取响应内容 -- 字符串
print(html.text)
sms.py
"""
# @TIME: 2021/10/16 下午9:24
# @FILE: sms.py
# @AUTHOR: HANG1720
# @COMMIT: 对接容联云短信平台
"""
import base64
import hashlib
import random
import time
import requests
class YunTongxun:
base_url = 'https://app.cloopen.com:8883'
def __init__(self, accountSid, accountToken, appId, templateId):
self.accountSid = accountSid
self.accountToken = accountToken
self.appId = appId
self.templateId = templateId
def get_request_url(self, sig):
"""
生成具体通信的业务url
:param sig: 签名
:return: 业务url
"""
self.url = self.base_url + '/2013-12-26/Accounts/%s/SMS/TemplateSMS?sig=%s' % (
self.accountSid, sig)
return self.url
def get_sig(self, timestamp):
"""
生成签名: MD5加密(账户Id + 账户授权令牌 + 时间戳).upper()
:param timestamp: 时间戳
:return: 签名
"""
s = self.accountSid + self.accountToken + timestamp
m = hashlib.md5()
m.update(s.encode())
return m.hexdigest().upper()
def get_timestamp(self):
"""
时间戳
:return: 时间戳
"""
return time.strftime('%Y%m%d%H%M%S')
def get_request_header(self, timestamp):
"""
生成请求头:
Authorization: Base64编码(账户Id + 冒号 + 时间戳)
:param timestamp: 时间戳
:return:
"""
s = self.accountSid + ":" + timestamp
auth = base64.b64encode(s.encode()).decode()
return {
"Accept": "application/json",
"Content-Type": "application/json;charset=utf-8",
"Authorization": auth
}
def get_request_body(self, phone, code):
"""
构建请求体
:param phone: 手机号
:param code: 验证码
:return: 请求体
"""
return {
"to": phone, "appId": self.appId,
"templateId": self.templateId,
"datas": [code, "1"]
}
def send_request(self, url, header, body):
"""
发送请求
:param url: 业务url
:param header: 请求头
:param body: 请求体
:return: 容联云响应内容
"""
res = requests.post(url=url, headers=header, json=body)
return res.text
def run(self, phone, code):
"""
程序入口
:return:
"""
# 时间戳
timestamp = self.get_timestamp()
sig = self.get_sig(timestamp)
url = self.get_request_url(sig)
print(url)
header = self.get_request_header(timestamp)
print(header)
body = self.get_request_body(phone, code)
data = self.send_request(url, header, body)
return data
if __name__ == '__main__':
# 请将下面字典的值 更换为自己在控制台获取到的 accountSid accountTokeappId
config = {
"accountSid": "8a216da87c304531017c87d6bd0c0d3f",
"accountToken": "66283b3d8f8349419efa14f296794b78",
"appId": "8a216da87c304531017c87d6be380d46",
"templateId": "1"
}
ytx = YunTongxun(**config)
# 请将手机号更换为自己的
code = random.randint(1000, 9999)
res = ytx.run("15190060586", code)
print(code)
print(res)