搜尋
首頁後端開發Python教學天翼开放平台免费短信验证码接口使用实例

对于目前众多的验证码解决方案来说,这个API有着中国电信这个重量级的运营商为靠山,应该是比较靠谱的了,而且还是免费的。

使用方式:
#定义app_id和app_secret
r = RandCode('app_id', 'app_secret')
#支持平台的两种接口方式
#方式1:自定义接收验证码的回调URL
r.send('phone number', 'http://yourdomain/rand_code.php', '3')
#方式2:自定义验证码内容
r.send_sms('phone number', 189189)

#!/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':phone,
    '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':phone,
    '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)

相关文章:

基于PHP实现短信验证码接口

短信验证码接口(容联运通讯)

PHP集成发送手机短信验证码、语音验证码接口函数及使用方法

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python的科學計算中如何使用陣列?Python的科學計算中如何使用陣列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何處理同一系統上的不同Python版本?您如何處理同一系統上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

與標準Python陣列相比,使用Numpy數組的一些優點是什麼?與標準Python陣列相比,使用Numpy數組的一些優點是什麼?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造

陣列的同質性質如何影響性能?陣列的同質性質如何影響性能?Apr 25, 2025 am 12:13 AM

數組的同質性對性能的影響是雙重的:1)同質性允許編譯器優化內存訪問,提高性能;2)但限制了類型多樣性,可能導致效率低下。總之,選擇合適的數據結構至關重要。

編寫可執行python腳本的最佳實踐是什麼?編寫可執行python腳本的最佳實踐是什麼?Apr 25, 2025 am 12:11 AM

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

Numpy數組與使用數組模塊創建的數組有何不同?Numpy數組與使用數組模塊創建的數組有何不同?Apr 24, 2025 pm 03:53 PM

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,內存效率段

Numpy數組的使用與使用Python中的數組模塊陣列相比如何?Numpy數組的使用與使用Python中的數組模塊陣列相比如何?Apr 24, 2025 pm 03:49 PM

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

CTYPES模塊與Python中的數組有何關係?CTYPES模塊與Python中的數組有何關係?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能