1. 基础环境

  • 微信公众号一个(我的是个人订阅号,不同的类型权限不同)
  • 有外网ip的服务器(centos7)

2. 服务器配置(以官方demo为例,具体见:官方文档

centos系统自带了python,因此不用再下载,如果没有自带python,需要先下载2.7及其以上版本的python。

2.1 安装依赖库

  • 安装pip
1
2
3
yum -y install epel-release
yum install python-pip
pip install --upgrade pip
  • 安装 web.py
1
pip install web.py
  • 安装libxml2, libxslt, lxml

这些库都是python自带的,如果没有需要安装。

  • 编辑代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
vi main.py
# -*- coding: utf-8 -*-
# filename: main.py
import web
urls = (
'/wx', 'Handle',
)
class Handle(object):
def GET(self):
return "hello, this is handle view"
if __name__ == '__main__':
app = web.application(urls, globals())
app.run()
  • 启动
1
python main.py 80

打开浏览器,输入服务器ip和路径,可以看到

image

  • 添加 handle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
vi handle.py
# -*- coding: utf-8 -*-
# filename: handle.py
import hashlib
import web
class Handle(object):
def GET(self):
try:
data = web.input()
if len(data) == 0:
return "hello, this is handle view"
signature = data.signature
timestamp = data.timestamp
nonce = data.nonce
echostr = data.echostr
token = "xxxx" #请按照公众平台官网\基本配置中信息填写
list = [token, timestamp, nonce]
list.sort()
sha1 = hashlib.sha1()
map(sha1.update, list)
hashcode = sha1.hexdigest()
print "handle/GET func: hashcode, signature: ", hashcode, signature
if hashcode == signature:
return echostr
else:
return ""
except Exception, Argument:
return Argument
  • 重新启动
1
python main.py 80

2. 微信公众号配置

在开发 > 基本配置中修改配置

image

image

其中的Token需要和服务器handle.py里的token一样。

点击“提交”之后,如果验证成功,则配置成功。