Python+Flask 微信企業號開發二之開啓回調模式

 一.  概述flask

    上文主要是關於微信主動發送消息給用戶, 這篇文章主要是用來描述如何開啓微信企業號的回調模式微信

 二 . 操做app

    1. 登錄微信企業號應用中心--個人應用--模式選擇--回調模式this

2. 代碼url

#coding=utf-8
from flask import abort, request
from wechatpy.enterprise import create_reply, parse_message
from wechatpy.enterprise.crypto import WeChatCrypto
from app.config import CORP_ID

from flask import Blueprint

#應用ID
sCorp_Id = CORP_ID

#回調模式裏面隨機生成的那個Token,EncodingAESKey
sToken = ''
sEncodingAESKey =""

crm = Blueprint('settings', __name__, url_prefix='/crm')
crypto = WeChatCrypto(token=sToken, encoding_aes_key=sEncodingAESKey, corp_id=sCorp_Id)

#對應回調模式中的URL
@crm.route('/weixin')
def weixin():
    echo_str = signature(request)
    if request.method == 'GET':
        return echo_str
    msg = parse_message(request.data)
    print(msg.type)
    if msg.type == 'text':
        reply = create_reply(msg.content, msg)
    else:
        reply = create_reply('Sorry, can not handle this for now', msg)
    return reply.render()


def signature(request):
    msg_signature = request.args.get('msg_signature', '')
    timestamp = request.args.get('timestamp', '')
    nonce = request.args.get('nonce', '')
    echo_str = request.args.get('echostr', '')
    print(request.args)
    try:
        #認證並對echo_str進行解密並返回明文
        echo_str = crypto.check_signature(msg_signature, timestamp, nonce, echo_str)
        print(echo_str)
    except Exception as ex:
        print(ex)
        print(request)
        abort(403)
    return echo_str


@crm.route('/hello')
def hello():
    return "hello! index"

3.說明code

按照如上進行配置就能夠成功開啓回調模式,而後就能夠成功接受發過來的消息。token

相關文章
相關標籤/搜索