Sky Wing open platform free SMS Authentication Code Interface Usage Example _python

Source: Internet
Author: User
Tags hmac sha1 urlencode

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

How to use:
#定义app_id和app_secret
r = Randcode (' app_id ', ' App_secret ')
#支持平台的两种接口方式
#方式1: Custom callback URL to receive authentication code
R.send (' phone number ', ' http://yourdomain/rand_code.php ', ' 3 ')
#方式2: Customizing Authenticode Content
R.send_sms (' phone number ', 189189)

Copy Code code as follows:

#!/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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.