Issues (41)

examples/echo-enterprise/app.py (1 issue)

1
from __future__ import absolute_import, unicode_literals
2
import os
3
from flask import Flask, request, abort, render_template
4
from wechatpy.enterprise.crypto import WeChatCrypto
5
from wechatpy.exceptions import InvalidSignatureException
6
from wechatpy.enterprise.exceptions import InvalidCorpIdException
7
from wechatpy.enterprise import parse_message, create_reply
8
9
10
TOKEN = os.getenv('WECHAT_TOKEN', '123456')
11
EncodingAESKey = os.getenv('WECHAT_ENCODING_AES_KEY', '')
12
CorpId = os.getenv('WECHAT_CORP_ID', '')
13
14
app = Flask(__name__)
15
16
17
@app.route('/')
18
def index():
19
    host = request.url_root
20
    return render_template('index.html', host=host)
21
22
23 View Code Duplication
@app.route('/wechat', methods=['GET', 'POST'])
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
24
def wechat():
25
    signature = request.args.get('msg_signature', '')
26
    timestamp = request.args.get('timestamp', '')
27
    nonce = request.args.get('nonce', '')
28
29
    crypto = WeChatCrypto(TOKEN, EncodingAESKey, CorpId)
30
    if request.method == 'GET':
31
        echo_str = request.args.get('echostr', '')
32
        try:
33
            echo_str = crypto.check_signature(
34
                signature,
35
                timestamp,
36
                nonce,
37
                echo_str
38
            )
39
        except InvalidSignatureException:
40
            abort(403)
41
        return echo_str
42
    else:
43
        try:
44
            msg = crypto.decrypt_message(
45
                request.data,
46
                signature,
47
                timestamp,
48
                nonce
49
            )
50
        except (InvalidSignatureException, InvalidCorpIdException):
51
            abort(403)
52
        msg = parse_message(msg)
53
        if msg.type == 'text':
54
            reply = create_reply(msg.content, msg).render()
55
        else:
56
            reply = create_reply('Can not handle this for now', msg).render()
57
        res = crypto.encrypt_message(reply, nonce, timestamp)
58
        return res
59
60
61
if __name__ == '__main__':
62
    app.run('127.0.0.1', 5001, debug=True)
63