1
|
|
|
# -*- coding: utf-8 -*- |
2
|
|
|
from __future__ import absolute_import, unicode_literals |
3
|
|
|
import os |
4
|
|
|
|
5
|
|
|
from flask import Flask, request, abort, render_template |
6
|
|
|
from wechatpy import parse_message, create_reply |
7
|
|
|
from wechatpy.utils import check_signature |
8
|
|
|
from wechatpy.exceptions import ( |
9
|
|
|
InvalidSignatureException, |
10
|
|
|
InvalidAppIdException, |
11
|
|
|
) |
12
|
|
|
|
13
|
|
|
# set token or get from environments |
14
|
|
|
TOKEN = os.getenv('WECHAT_TOKEN', '123456') |
15
|
|
|
AES_KEY = os.getenv('WECHAT_AES_KEY', '') |
16
|
|
|
APPID = os.getenv('WECHAT_APPID', '') |
17
|
|
|
|
18
|
|
|
app = Flask(__name__) |
19
|
|
|
|
20
|
|
|
|
21
|
|
|
@app.route('/') |
22
|
|
|
def index(): |
23
|
|
|
host = request.url_root |
24
|
|
|
return render_template('index.html', host=host) |
25
|
|
|
|
26
|
|
|
|
27
|
|
|
@app.route('/wechat', methods=['GET', 'POST']) |
28
|
|
|
def wechat(): |
29
|
|
|
signature = request.args.get('signature', '') |
30
|
|
|
timestamp = request.args.get('timestamp', '') |
31
|
|
|
nonce = request.args.get('nonce', '') |
32
|
|
|
encrypt_type = request.args.get('encrypt_type', 'raw') |
33
|
|
|
msg_signature = request.args.get('msg_signature', '') |
34
|
|
|
try: |
35
|
|
|
check_signature(TOKEN, signature, timestamp, nonce) |
36
|
|
|
except InvalidSignatureException: |
37
|
|
|
abort(403) |
38
|
|
|
if request.method == 'GET': |
39
|
|
|
echo_str = request.args.get('echostr', '') |
40
|
|
|
return echo_str |
41
|
|
|
|
42
|
|
|
# POST request |
43
|
|
|
if encrypt_type == 'raw': |
44
|
|
|
# plaintext mode |
45
|
|
|
msg = parse_message(request.data) |
46
|
|
|
if msg.type == 'text': |
47
|
|
|
reply = create_reply(msg.content, msg) |
48
|
|
|
else: |
49
|
|
|
reply = create_reply('Sorry, can not handle this for now', msg) |
50
|
|
|
return reply.render() |
51
|
|
|
else: |
52
|
|
|
# encryption mode |
53
|
|
|
from wechatpy.crypto import WeChatCrypto |
54
|
|
|
|
55
|
|
|
crypto = WeChatCrypto(TOKEN, AES_KEY, APPID) |
56
|
|
|
try: |
57
|
|
|
msg = crypto.decrypt_message( |
58
|
|
|
request.data, |
59
|
|
|
msg_signature, |
60
|
|
|
timestamp, |
61
|
|
|
nonce |
62
|
|
|
) |
63
|
|
|
except (InvalidSignatureException, InvalidAppIdException): |
64
|
|
|
abort(403) |
65
|
|
|
else: |
66
|
|
|
msg = parse_message(msg) |
67
|
|
|
if msg.type == 'text': |
68
|
|
|
reply = create_reply(msg.content, msg) |
69
|
|
|
else: |
70
|
|
|
reply = create_reply('Sorry, can not handle this for now', msg) |
71
|
|
|
return crypto.encrypt_message(reply.render(), nonce, timestamp) |
72
|
|
|
|
73
|
|
|
|
74
|
|
|
if __name__ == '__main__': |
75
|
|
|
app.run('127.0.0.1', 5001, debug=True) |
76
|
|
|
|