Python3阿里大魚簡訊驗證碼

weixin_33912246發表於2018-05-27

阿里大魚.py

#encoding:utf-8

import hashlib

from timeimport time

import logging

import requests

class AlidayuAPI(object):

APP_KEY_FIELD ='ALIDAYU_APP_KEY'

    APP_SECRET_FIELD ='ALIDAYU_APP_SECRET'

    SMS_SIGN_NAME_FIELD ='ALIDAYU_SIGN_NAME'

    SMS_TEMPLATE_CODE_FIELD ='ALIDAYU_TEMPLATE_CODE'

    def __init__(self, app=None):

self.url ='https://eco.taobao.com/router/rest'

        self.headers = {

'Content-type':'application/x-www-form-urlencoded;charset=UTF-8',

            "Cache-Control":"no-cache",

            "Connection":"Keep-Alive",

        }

if app:

self.init_app(app)

def init_app(self,app):

config = app.config

try:

self.key = config[self.APP_KEY_FIELD]

self.secret = config[self.APP_SECRET_FIELD]

self.sign_name = config[self.SMS_SIGN_NAME_FIELD]

self.api_params = {

'sms_free_sign_name': config[self.SMS_SIGN_NAME_FIELD],

                'sms_template_code': config[self.SMS_TEMPLATE_CODE_FIELD],

                'extend':'',

                'sms_type':"normal",

                "method":"alibaba.aliqin.fc.sms.num.send",

                "app_key":self.key,

                "format":"json",

                "v":"2.0",

                "partner_id":"",

                "sign_method":"md5",

            }

except Exception as e:

logging.error(e.args)

raise ValueError('請填寫正確的阿里大魚配置!')

def send_sms(self,telephone,**params):

self.api_params['timestamp'] =str(int(time() *1000))

self.api_params['sms_param'] =str(params)

self.api_params['rec_num'] = telephone

newparams ="".join(["%s%s" % (k, v)for k, vin sorted(self.api_params.items())])

newparams =self.secret + newparams +self.secret

sign = hashlib.md5(newparams.encode("utf-8")).hexdigest().upper()

self.api_params['sign'] = sign

resp = requests.post(self.url,params=self.api_params,headers=self.headers)

data = resp.json()

try:

result = data['alibaba_aliqin_fc_sms_num_send_response']['result']['success']

return result

except:

print('='*10)

print("阿里大於錯誤資訊:",data)

print('='*10)

return False

主app.py

def create_app():

    app = Flask(__name__)

    alidayu.init_app(app)

    return app

app = create_app()

if __name__ =='__main__':

app.run()

檢視層.py


@bp.route('/sms_captcha/',methods=['POST'])

def sms_captcha():

#    時間戳  手機  引

#md5(ts+telephone+salt)

    form = SMSCaptchaForm(request.form)

if form.validate():

    telephone = form.telephone.data

    captcha = Captcha.gene_text(number=4)

    zlcache.set(telephone, captcha)

    print("傳送的簡訊驗證碼是:",captcha)

    send_sms_captcha.delay(telephone,captcha)

     if alidayu.send_sms(telephone,code = captcha):

        zlcache.set(telephone, captcha)

            return restful.success()

     else:

         return restful.params_error()

else:

return restful.params_error(message="引數錯誤")

相關文章