Skip to content

Instantly share code, notes, and snippets.

@dequn
Last active August 24, 2018 06:09
Show Gist options
  • Save dequn/e28fad8498c33f3ad2be59d1c3abc48d to your computer and use it in GitHub Desktop.
Save dequn/e28fad8498c33f3ad2be59d1c3abc48d to your computer and use it in GitHub Desktop.
阿里云短信api url构造
import base64
import datetime
import hashlib
import hmac
import json
import urllib.parse
import uuid
access_key_id = ''
access_secret = ''
# 替换上边两个参数
system_params = {
'SignatureMethod': 'HMAC-SHA1',
'SignatureVersion': '1.0',
'AccessKeyId': access_key_id
}
business_params = {
'Action': 'SendSms',
'Version': '2017-05-25',
'RegionId': 'cn-hangzhou',
}
def generate_api_url(template_code, sign_name, phone_numbers, template_params):
"""
:param template_code: 短信模板编号
:param sign_name: 短信签名
:param phone_numbers: 收信人,可以是结合、列表、字符串
:param template_params: 短信模板参数
:return: 调用URL
"""
assert sign_name is not None and isinstance(sign_name, str), '签名参数不合法'
assert template_code is not None and isinstance(template_code, str), '模板参数不合法'
assert phone_numbers is not None and (
isinstance(phone_numbers, set) or
isinstance(phone_numbers, list) or
isinstance(phone_numbers, str)
), '手机号码不合法'
assert template_params is not None and (
isinstance(template_params, dict) or
isinstance(template_params, str)
), '模板参数不合法'
params = dict()
params.update(system_params)
params.update(business_params)
params['SignatureNonce'] = str(uuid.uuid1())
params['SignName'] = sign_name
params['TemplateCode'] = template_code
dt = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=0), 'GMT'))
params['Timestamp'] = dt.strftime('%Y-%m-%dT%H:%M:%SZ')
if isinstance(phone_numbers, set) or isinstance(phone_numbers, list):
params['PhoneNumbers'] = ','.join(phone_numbers)
else:
params['PhoneNumbers'] = phone_numbers
if isinstance(template_params, dict):
params['TemplateParam'] = json.dumps(template_params, separators=(',', ':'))
else:
params['TemplateParam'] = template_params
sorted_params = sorted([(key, val) for key, val in params.items()], key=lambda t: t[0])
query_string = urllib.parse.urlencode(sorted_params)
query_string2 = urllib.parse.quote(query_string, safe='')
string_to_sign = 'GET&%%2F&%s' % (query_string2)
hmac_sha1 = hmac.new(
bytes(access_secret + '&', encoding='utf-8'),
bytes(string_to_sign, encoding='utf-8'),
hashlib.sha1
)
temp_sign = hmac_sha1.digest()
base64_sign = base64.standard_b64encode(temp_sign)
encode_sign = urllib.parse.quote(base64_sign, safe='')
url = 'http://dysmsapi.aliyuncs.com/?Signature=%s&%s' % (encode_sign, query_string)
return url
# if __name__ == '__main__':
# params = "{\"date\":\"2018-08-23\",\"type\":\"洪水灾害\"}"
# print(generate_api_url('SMS_142950219', '新视野', '13070175160', params))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment