找回密码
 立即注册
首页 python Python-Web 查看内容
import shortuuid
from datetime import datetime
from urllib.parse import unquote, quote_plus
import hmac
import base64
import hashlib
import requests


class AliyunCode(object):
    access_key_id = 'xxxxx'
    access_secret = 'xxxxx'
    sign_name = '签名'
    phone = '13843848484'
    templace_code = 'sms'
    url = 'http://dysmsapi.aliyuncs.com/'


    @classmethod
    def __set_encode(cls, value):
        return quote_plus(value).replace('+', '%20').replace('*', '%2A"').replace('%7E', '~')

    @classmethod
    def __set_params(cls, phone, access_key_id, sign_name, code, template_code):
        params = dict()
        params['SignatureMethod'] = 'HMAC-SHA1'
        params['SignatureNonce'] = shortuuid.uuid()
        params['AccessKeyId'] = access_key_id
        params['SignatureVersion'] = '1.0'
        params['Timestamp'] = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
        params['Action'] = 'SendSms'
        params['Version'] = '2017-05-25'
        params['RegionId'] = 'cn-hangzhou'
        params['PhoneNumbers'] = phone
        params['SignName'] = sign_name
        params['TemplateParam'] = r'{"code": %s}' %code
        params['TemplateCode'] = template_code
        if 'Signature' in params:
            params.pop('Signature')
        print(datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'))
        sorted_params = sorted(params)
        map_params = list(map(lambda x : {x: params[x]}, sorted_params))
        param_str = ''
        for i in map_params:
            for k, v in i.items():
                param_str = param_str + '&' +cls.__set_encode(k) + '=' + cls.__set_encode(v)

        return param_str

    @classmethod
    def __set_sign(cls, params, access_secret):
        param_sign = params.lstrip('&')
        param_last = 'GET' + '&' + cls.__set_encode('/') + '&' + cls.__set_encode(param_sign)
        access_secret_with = access_secret + '&'
        hmac_param = hmac.new(access_secret_with.encode('utf-8'), param_last.encode('utf-8'), digestmod=hashlib.sha1)
        sign_str = hmac_param.digest()
        sign = cls.__set_encode(base64.b64encode(sign_str).decode())
        return sign

    @classmethod
    def send_sms(cls, phone, access_key_id, sign_name, code, template_code, access_secret):
        params = cls.__set_params(phone, access_key_id, sign_name, code, template_code)
        sign = cls.__set_sign(params, access_secret)
        get_str = cls.url + '?Signature=%s%s' %(sign, params)
        print(requests.get(get_str).text)

if __name__ == '__main__':
    a = AliyunCode
    a.send_sms(a.phone, a.access_key_id,a.sign_name, '2222', a.templace_code, a.access_secret)


分享至 : QQ空间
收藏

0 个回复

您需要登录后才可以回帖 登录 | 立即注册