微信服务器后台-收发消息

app.py
# -*- coding:utf-8 -*-

from flask import Flask, request
import time
import xml.etree.ElementTree as et

import hashlib

app = Flask(__name__)


@app.route('/wx/', methods=['GET', 'POST'])
def wechat():
    if request.method == 'GET':
        token = 'groundwalker'
        data = request.args
        signature = data.get('signature', '')
        timestamp = data.get('timestamp', '')
        nonce = data.get('nonce', '')
        echostr = data.get('echostr', '')

        list = [token, timestamp, nonce]
        list.sort()

        s = list[0] + list[1] + list[2]

        hascode = hashlib.sha1(s.encode('utf-8')).hexdigest()

        if hascode == signature:
            return echostr
        else:
            return ""

    if request.method == 'POST':
        xmldata = request.data
        xml_rec = et.fromstring(xmldata)

        ToUserName = xml_rec.find('ToUserName').text
        FromUserName = xml_rec.find('FromUserName').text
        MsgType = xml_rec.find('MsgType').text
        Content = xml_rec.find('Content').text
        MsgId = xml_rec.find('MsgId').text

        # 收到什么就返回什么
        def reply(xmldata):
            xml_rec = et.fromstring(xmldata)

            my_id = xml_rec.find('ToUserName').text
            fans_id = xml_rec.find('FromUserName').text
            create_time = time.time()
            msg_type = xml_rec.find('MsgType').text
            content = xml_rec.find('Content').text

            message = '''/n/n%s/n/n/n''' % (fans_id, my_id, create_time, msg_type, content)

            return str.encode(message)
        print(reply(xmldata))
        return reply(xmldata)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)

你可能感兴趣的:(微信服务器后台-收发消息)