#!/usr/bin/python3
# -*- coding: utf-8 -*-
#阿里云短信API SDK Python3版
import urllib.request
import time, datetime
import uuid
import base64, json
import hmac, hashlib
class SMS():
_prefix_url = "https://dysmsapi.aliyuncs.com/?"
def __init__(self, ACCESSKEYID, ACCESSSECRET, SIGN_NAME):
self.__accesskeyid = ACCESSKEYID
self.__accesssecret = ACCESSSECRET
self.__sign_name = SIGN_NAME
#发送短信
def send_sms(self, mobiles, tpl_code, tpl_params):
p_dict = {
"SignatureMethod": "HMAC-SHA1",
"SignatureNonce": uuid.uuid4().hex,
"AccessKeyId": self.__accesskeyid,
"SignatureVersion": "1.0",
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", datetime.datetime.utcnow().timetuple()),
"Format": "JSON",
"Action": "SendSms",
"Version": "2017-05-25",
"RegionId": "cn-hangzhou",
"PhoneNumbers": "{0}".format(mobiles),
"SignName": self.__sign_name,
"TemplateParam": json.dumps(tpl_params, ensure_ascii=False),
"TemplateCode": tpl_code,
"OutId": "123"
}
eps = ""
for key in sorted(p_dict.keys()):
eps += key + '=' + urllib.parse.quote(p_dict[key]) + '&'
eps = eps.rstrip("&")
sign_str = self.signature("GET&%2F&" + urllib.parse.quote(eps))
url = "{0}Signature={1}&{2}".format(self._prefix_url, sign_str, eps)
r = urllib.request.urlopen(url)
return json.loads(r.read())
#签名函数
def signature(self, prepare_str):
k = "{0}{1}".format(self.__accesssecret, "&")
r = hmac.new(k.encode(), prepare_str.encode(), hashlib.sha1).digest()
base_str = base64.b64encode(r).decode()
return urllib.parse.quote_plus(base_str)
if __name__ == "__main__":
entity = SMS(ACCESSKEYID = "", ACCESSSECRET = "", SIGN_NAME = "比特量化")
_tpl_code = "SMS_800001234"
_tpl_params = {
"code": "1234"}
result = entity.send_sms("165501809", _tpl_code, _tpl_params)
print(result)
阿里云短信API SDK Python3版
猜你喜欢
转载自blog.csdn.net/bitquant/article/details/105795816
今日推荐
周排行