For the current number of authentication code solutions, this API with China Telecom, the heavyweight operator as a backer, should be more reliable, but also free. For more information, see: http://open.189.cn
#!/usr/bin/env python
# Coding:utf-8
From time import strftime, localtime
Import Urllib, URLLIB2, JSON
Import HMAC, Hashlib
Class Randcode (object):
app_id = ' '
App_secret = ' '
Access_token = ' '
Randcode_token = ' '
Token_api = ' Https://oauth.api.189.cn/emp/oauth2/v2/access_token '
Randcode_token_api = ' Http://api.189.cn/v2/dm/randcode/token '
Randcode_send_api = ' Http://api.189.cn/v2/dm/randcode/send '
Randcode_sendsms_api = ' Http://api.189.cn/v2/dm/randcode/sendSms '
def __init__ (self, app_id= ', app_secret= ', access_token= '):
Self. app_id = app_id or randcode.app_id
Self. App_secret = App_secret or Randcode.app_secret
Self. Access_token = Access_token or Self.__fetch_access_token ()
Self. Randcode_token = Self.__fetch_randcode_token ()
def send (self, phone, url, exp_time):
result = False
If self. Access_token and self. Randcode_token:
data = {
' app_id ': self. APP_ID,
' Access_token ': self. Access_token,
' token ': self. Randcode_token,
' Phone ':p hone,
' url ': URL,
' Exp_time ': Exp_time,
' Timestamp ': Self.__date_time (),
}
data = self.__build_request_string (data)
data = self.__data_sign (data)
If data:
res = Self.__request_data (' Post ', data, self. RANDCODE_SEND_API)
Json_data = Json.loads (res)
If json_data[' res_code '] = = 0:
result = True
return result
def send_sms (self, phone, randcode, exp_time= ' 2 '):
result = False
If self. Access_token and self. Randcode_token:
data = {
' app_id ': self. APP_ID,
' Access_token ': self. Access_token,
' token ': self. Randcode_token,
' Phone ':p hone,
' Randcode ': Str (randcode),
' Exp_time ': Exp_time,
' Timestamp ': Self.__date_time (),
}
data = self.__build_request_string (data)
data = self.__data_sign (data)
If data:
res = Self.__request_data (' Post ', data, self. RANDCODE_SENDSMS_API)
Json_data = Json.loads (res)
If json_data[' res_code '] = = 0:
result = True
return result
Pass
def __request_data (self, method, data, URL):
If Isinstance (data, dict):
data = Urllib.urlencode (data)
If method = = ' Post ':
req = Urllib2. Request (URL, data)
Else
url = '%s?%s '% (URL, data)
req = Urllib2. Request (URL)
Return Urllib2.urlopen (req). Read ()
def __fetch_access_token (self):
Access_token = self. Access_token
if Access_token = = ':
data = {
' Grant_type ': ' Client_credentials ',
' app_id ': self. APP_ID,
' App_secret ': self. App_secret,
}
res = Self.__request_data (' Post ', data, self. TOKEN_API)
Json_data = Json.loads (res)
If json_data[' res_code '] = = ' 0 ':
Access_token = json_data[' Access_token ']
Else
Raise ValueError (json_data[' res_message ')
Return Access_token
def __fetch_randcode_token (self):
result = '
if self. Access_token!= ':
data = {
' app_id ': self. app_id,
' Access_token ': self. Access_token,
' timestamp ': Self.__date_time (),
}
data = self.__build_request_string (data)
data = self.__data_sign (data)
if data:
res = self.__request_data (' Get ', data, self. RANDCODE_TOKEN_API)
json_data = json.loads (res)
if json_ data[' res_code '] = = 0:
result = json_data[' token ']
else:
raise valueerror (json_data[' res_message ')
return result
def __data_sign (self, data):
result = '
If data:
If Isinstance (data, dict):
data = self.__build_request_string (data)
Sign = Hmac.new (self. App_secret, Urllib.urlencode (data), HASHLIB.SHA1). Digest ()
Elif isinstance (data, Unicode):
Sign = Hmac.new (self. App_secret, data, HASHLIB.SHA1). Digest ()
If data:
result = "%s&sign=%s"% (data, urllib.quote (Sign.encode (' base64 '). Strip ())
return result
def __build_request_string (self, dict):
Keys = Dict.keys ()
Keys.sort ()
Return ' & '. Join ([key + "=" + Dict[key] for key in keys])
def __date_time (self):
Return strftime ("%y-%m-%d%h:%m:%s", localtime ())
if __name__ = = ' __main__ ':
r = Randcode (' app_id ', ' App_secret ')
R.send (' phone number ', ' http://yourdomain/rand_code.php ', ' 3 ')
R.send_sms (' phone number ', 189189)