Skip to content

Instantly share code, notes, and snippets.

@lihnux
Created January 19, 2018 02:53
Show Gist options
  • Save lihnux/ff7fabb867f40ff37466659bb46c3fba to your computer and use it in GitHub Desktop.
Save lihnux/ff7fabb867f40ff37466659bb46c3fba to your computer and use it in GitHub Desktop.
2018.01.19 -- 可用的Python3的阿里云短信发送的代码
#coding: utf-8
import uuid
import datetime
import hmac
import base64
import requests
from urllib.parse import urlencode, quote
class AliSMS():
def __init__(self):
# https://help.aliyun.com/document_detail/56189.html?spm=5176.doc54229.6.576.0sHRgn
self.access_key_id = ""
self.access_key_secret = ""
self.timestamp = datetime.datetime.utcnow().isoformat("T")
self.signature_method = "HMAC-SHA1"
self.signature_version = "1.0"
self.signature_nonce = str(uuid.uuid4())
self.signature = ""
self.action = "SendSms"
self.version = "2017-05-25"
self.region_id = "cn-hangzhou"
self.phone_numbers = []
self.sign_name = ""
self.template_code = ""
self.template_params = {}
self.out_id = ""
self.gateway = "http://dysmsapi.aliyuncs.com"
def send_sms(self, phone):
self.phone_numbers.append(phone)
query_string = self.build_query_string()
response = requests.get(self.gateway + "?" + query_string)
print(response)
def build_query_string(self):
query = []
query.append(("AccessKeyId", self.access_key_id))
query.append(("Timestamp", self.timestamp))
query.append(("SignatureMethod", self.signature_method))
query.append(("SignatureVersion", self.signature_version))
query.append(("SignatureNonce", self.signature_nonce))
query.append(("Action", self.action))
query.append(("Version", self.version))
query.append(("RegionId", self.region_id))
query.append(("PhoneNumbers", ",".join(self.phone_numbers)))
query.append(("SignName", self.sign_name))
query.append(("TemplateCode", self.template_code))
query.append(("TemplateParam", "{\"code\":\"1234\"}"))
query = sorted(query, key=lambda key: key[0])
query_string = ""
for item in query:
query_string += quote(item[0], safe="~") + "=" + quote(item[1], safe="~") + "&"
query_string = query_string[:-1]
tosign = "GET&%2F&" + quote(query_string, safe="~")
secret = self.access_key_secret + "&"
hmb = hmac.new(secret.encode("utf-8"), tosign.encode("utf-8"), "sha1").digest()
self.signature = quote(base64.standard_b64encode(hmb).decode("ascii"), safe="~")
query_string += "&" + "Signature=" + self.signature
print(query_string)
return query_string
if __name__ == '__main__':
print("alisms, test")
sender = AliSMS()
sender.send_sms("13088888888")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment