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