python3 微信公众平台开发--使用web.py搭建一个微信服务

1. 搭建微信服务器

web.py安装

pip install web.py==0.40.dev0    # python3
pip install web.py    # python2

服务端代码

1.  main.py代码

# -*- coding: utf-8 -*-
# filename: main.py
import web
urls = (
    '/wx', 'Handle',)
class Handle(object):
    def GET(self):
        return "hello, this is a test"
if __name__ == '__main__':
    app = web.application(urls, globals())
    app.run()

2. 如果出现“socket.error: No socket could be created“错误信息,可能为80端口号被占用,可能是没有权限,请自行查询解决办法。如果遇见其他错误信息,请到 web.py官方文档 学习webpy 框架3)

执行命令:

sudo python main.py 80 。

3. 浏览器输入http://外网IP:80/wx  

如下图,一个简单的web应用已搭建。

2.接口配置信息填写

2.1 微信公众号端

url: 填写对应的网址,比如我的是wx.chenxm.cc/wx

token: 可以填写随机字符串,不建议填写纯数字

2.2 服务端代码修改

main.py

# -*- coding: utf-8 -*-
# filename: main.py
import web
from handle import Handle
urls = (
    '/wx',)
if __name__ == '__main__':
    app = web.application(urls, globals())
    app.run()
handle.py

业务逻辑图

# -*- coding: utf-8 -*-
# filename: handle.py
import hashlib
import web
class Handle(object):
    def GET(self):
        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 = "a123456789"  # 请按照公众平台官网\基本配置中信息填写
        li = [timestamp, nonce, token]
        query_string = ''.join(li)
        sha1 = hashlib.sha1()
        # python3写法
        sha1.update(bytes(query_string, encoding='utf-8'))
        # python2写法
        # sha1.update(query_string)
        hashcode = sha1.hexdigest()
        # print("------handle/GET func: hashcode, signature-----")
        # print("hashcode--->", hashcode)
        # print("signature-->", signature)
        if hashcode == signature:
            return echostr
        else:
            return ""

重新执行命令:

sudo python main.py 80


相关文章

Python中的函数(二) 在上一篇文章中提到了Python中函数的定...
Python中的字符串 可能大多数人在学习C语言的时候,最先接触...
Python 面向对象编程(一) 虽然Python是解释性语言,但是它...
Python面向对象编程(二) 在前面一篇文章中谈到了类的基本定...
Python中的函数(一) 接触过C语言的朋友对函数这个词肯定非...
在windows下如何快速搭建web.py开发框架 用Python进行web开发...