python3 阿里云短信发送Demo

最近在把代码由python2.7升级到3.6的过程中, 遇到阿里云的短信接口改用python3就报错的问题, 折腾了两天,总算能使了.

在阿里官网(https://yq.aliyun.com/articles/59928)例子的基础上, 修改如下:

1. APPCODE简单身份认证模式

# coding=utf-8
import requests  # pip install requests

HOST = "sms.market.alicloudapi.com"
appcode = '你自己的AppCode'
querys = {
    'ParamString': '{"name":"xx先生","sid":"17052613"}',
    "RecNum": "18620610611", 
    "TemplateCode": "SMS_69030091",
    "SignName": "公信刻" }
host = 'http://{HOST}/singleSendSms'.format(HOST=HOST)
headers = {'Authorization': 'APPCODE {appcode}'.format(appcode=appcode)}
r = requests.get(host, params=querys, headers=headers)
if r.ok:
    print(r.json())

2.  AppKey&AppSecret签名认证模式

#encoding=utf-8
from __future__ import print_function
__author__ = 'williezh'
import base64
import hashlib
import hmac
import string
import time
import uuid

try:  # PY3
    from http.client import HTTPConnection
    from urllib.parse import quote
    ensure_binary = lambda v: v.encode() if isinstance(v, str) else v
    ensure_str = lambda v: v.decode() if isinstance(v, bytes) else v
except ImportError:  # PY2
    from httplib import HTTPConnection
    from urllib import quote
    ensure_binary = lambda v: v
    ensure_str = lambda v: v


class SMSClient:
    def __init__(self, app_key, app_secret):
        self.__app_key, self.__app_secret = app_key, app_secret

    def send(self, receiver, sign, template_code, parameters=''):
        print(receiver, sign, template_code, parameters)
        self.__host = 'sms.market.alicloudapi.com'
        self.__str_uri = '/singleSendSms?ParamString=%s&RecNum=%s&SignName=%s&TemplateCode=%s' % (parameters, receiver, sign, template_code)
        print(self.__str_uri)
        uri = quote(self.__str_uri, safe=string.printable)
        self.build_headers()
        self.__connection = HTTPConnection(self.__host, 80)
        self.__connection.connect()
        self.__connection.request('GET', uri, headers=self.__headers)
        response = self.__connection.getresponse()
        print(response.status, response.getheaders(), response.read())

    def build_headers(self):
        headers = dict()
        headers['X-Ca-Key'] = self.__app_key
        headers['X-Ca-Nonce'] = str(uuid.uuid4())
        headers['X-Ca-Timestamp'] = str(int(time.time() * 1000))
        headers['X-Ca-Signature-Headers'] = 'X-Ca-Key,X-Ca-Nonce,X-Ca-Timestamp'
        str_header = '\n'.join('%s:%s' % (k, headers[k]) for k in ['X-Ca-Key','X-Ca-Nonce','X-Ca-Timestamp'])
        str_to_sign = '%s\n\n\n\n\n%s\n%s' % ('GET', str_header, self.__str_uri)
        headers['X-Ca-Signature'] = self.__get_sign(str_to_sign, self.__app_secret)
        self.__headers = headers

    def __get_sign(self, source, secret):
        h = hmac.new(ensure_binary(secret), ensure_binary(source), hashlib.sha256)
        signature = base64.encodestring(h.digest()).strip()
        return ensure_str(signature)

cli = SMSClient(app_key="APP_KEY", app_secret="APP_SECRET")
cli.send('18620610611,1862061062', '公信刻', 'SMS_67670312', '{"name":"xx先生","sid":"17052613","op":"修改密码","sn":"0324"}')


你可能感兴趣的:(python)