最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]尝试把Python版微信SDK wechat-python-sdk集成到Flask中

Flask crifan 3616浏览 0评论

背景是之前已经可以让Helloworld之类的东西在flask上面跑起来了:

[记录]CentOS中继续研究Flask服务器

然后,之前知道存在Python的微信SDK开发包:

[整理]微信公众号开发 Python SDK

找到好几个,目前决定先去试试:

doraemonext/wechat-python-sdk: 微信公众平台 Python 开发包 (wechat-python-sdk)

需要把这个Python版的微信的SDK,继承到Flask中

且确保能正常了连接微信的公众号

去安装:

[记录]安装Python微信SDK包:wechat-sdk

继续参考:

1. SDK 快速介绍 – wechat-python-sdk

微信 全局返回码说明

参考:

2. 官方接口 – wechat-python-sdk

同时再去参考:

另外一个微信的Python的SDK:

jxtech/wechatpy: WeChat SDK for Python

中的实例代码:

wechatpy/app.py at master · jxtech/wechatpy

去登录微信公众号,开启开发模式:

[记录]开启并设置微信公众号的开发模式

此处微信号的设置参数是:

AppID(应用ID): wx9xxxxxxxxxxxxxxd

AppSecret(应用密钥): 8xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxd

URL: http://hd.webonn.com/wechat_auth

Token: sipevents

EncodingAESKey: bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxt

搜:

python 微信开发 flask

参考:

python,flask,SAE(新浪云),搭建开发微信公众账号 – 开源中国社区

Flask+SAE快速打造微信公众帐号(有码) – Happy Idle Kid – 博客频道 – CSDN.NET

lhysrc/weixin_python: 微信公众号开发,python Flask

然后想办法,去Flask中,使用上这个库

参考:

wechatpy/app.py at master · jxtech/wechatpy

python,flask,SAE(新浪云),搭建开发微信公众账号 – 开源中国社区

gunicorn -w 4 -b 127.0.0.1:8080 wechat_auth:app

结果:

[已解决]Python代码运行出错:SyntaxError: Non-ASCII character \xe5 in file on line 12, but no encoding declared

-rw-r–r– 1 root root 1.6K Aug 18  2016 wechat_auth.py
(SIPEvents) ➜  SIPEvents gunicorn -w 4 -b 127.0.0.1:8080 wechat_auth:app
[2016-08-18 20:50:36 +0000] [22309] [INFO] Starting gunicorn 19.6.0
[2016-08-18 20:50:36 +0000] [22309] [INFO] Listening at: http://127.0.0.1:8080 (22309)
[2016-08-18 20:50:36 +0000] [22309] [INFO] Using worker: sync
[2016-08-18 20:50:36 +0000] [22314] [INFO] Booting worker with pid: 22314
[2016-08-18 20:50:36 +0000] [22316] [INFO] Booting worker with pid: 22316
[2016-08-18 20:50:36 +0000] [22318] [INFO] Booting worker with pid: 22318
[2016-08-18 20:50:36 +0000] [22321] [INFO] Booting worker with pid: 22321

去启用开发模式:

log输出:

[2016-08-18 20:52:27 +0000] [22316] [ERROR] Error handling request /wechat_auth?signature=f0e35ccbc812f28997a3bc093e6f8c53371c87fc&echostr=4275307926626758575&timestamp=1471524747&nonce=973760365
Traceback (most recent call last):
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/workers/sync.py”, line 135, in handle
    self.handle_request(listener, req, client, addr)
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/workers/sync.py”, line 176, in handle_request
    respiter = self.wsgi(environ, resp.start_response)
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py”, line 2000, in __call__
    return self.wsgi_app(environ, start_response)
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py”, line 1991, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py”, line 1567, in handle_exception
    reraise(exc_type, exc_value, tb)
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py”, line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py”, line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py”, line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py”, line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File “/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py”, line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File “/usr/share/nginx/html/SIPEvents/wechat_auth.py”, line 27, in wechat
    signature = request.args.get(‘signature’, ”)
NameError: global name ‘request’ is not defined

参考:

weixin_python/WeiXin.py at master · lhysrc/weixin_python

把:

from flask import Flask

换成:

from flask import Flask, g, request, make_response

即可。

然后后来出现:

[已解决]Flask中调用wechat_sdk出错:AttributeError: function object has no attribute check_signature

然后就可以正常的通过微信公众号的开发模式的验证了:

对应的Flask的gunicorn的输出是:

(SIPEvents) ➜  SIPEvents gunicorn -w 4 -b 127.0.0.1:8080 wechat_auth:app
[2016-08-18 21:24:10 +0000] [22671] [INFO] Starting gunicorn 19.6.0
[2016-08-18 21:24:10 +0000] [22671] [INFO] Listening at: http://127.0.0.1:8080 (22671)
[2016-08-18 21:24:10 +0000] [22671] [INFO] Using worker: sync
[2016-08-18 21:24:10 +0000] [22676] [INFO] Booting worker with pid: 22676
[2016-08-18 21:24:10 +0000] [22677] [INFO] Booting worker with pid: 22677
[2016-08-18 21:24:10 +0000] [22682] [INFO] Booting worker with pid: 22682
[2016-08-18 21:24:10 +0000] [22683] [INFO] Booting worker with pid: 22683

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:35]:
signature=5e9f96b9e3b741dbefea915db6072d4cf990c66d, timestamp=1471526655, nonce=2012936672, echostr=5043377447722548991, encrypt_type=safe, msg_signature=

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:38]:
wechat check_signature OK

<div–<——————————————————————————

-》此时,可以通过输出看出来:

在进行微信的开发模式的验证的时候,微信发给我们服务器的验证消息中,并没有包含对应的msg_signature

-》所以代码中,就应该去掉才对,变成:

#!/usr/bin/python
# -*- coding: UTF-8 -*-  
from flask import Flask, g, request, make_response
from wechat_sdk import WechatConf
from wechat_sdk import WechatBasic
app = Flask(__name__)
# app.debug=True
wechatConf = WechatConf(
    token=’sipevents’, 
    appid=’wx9xxxxxxxxxxxxxxd’,
    appsecret=’8xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxd’,
    # 可选项:normal/compatible/safe,分别对应于 明文/兼容/安全 模式
    encrypt_mode=’safe’,
    # 如果传入此值则必须保证同时传入 token, appid
    encoding_aes_key=’bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxt’
)
wechat = WechatBasic(conf=wechatConf)
@app.route(“/”)
def hello():
    return “Hello SIPEvents!”
@app.route(‘/wechat_auth’, methods=[‘GET’, ‘POST’])
def wechat_auth():
    signature = request.args.get(‘signature’, ”)
    timestamp = request.args.get(‘timestamp’, ”)
    nonce = request.args.get(‘nonce’, ”)
    echostr = request.args.get(‘echostr’, ”)
    encrypt_type = request.args.get(‘encrypt_type’, ”)
    app.logger.debug(‘signature=%s, timestamp=%s, nonce=%s, echostr=%s, encrypt_type=%s, msg_signature=%s’, signature, timestamp, nonce, echostr, encrypt_type, msg_signature)
    if wechat.check_signature(signature, timestamp, nonce):
        app.logger.debug(“wechat check_signature OK”)
        if request.method == ‘GET’ :
            return make_response(echostr)
        else :
            return make_response(“current not support wechat auth POST”)
    else :
        app.logger.debug(“wechat check_signature wrong”)
        return make_response(“wechat auth failed”)
if __name__ == ‘__main__’:
    app.run(debug=True)

转载请注明:在路上 » [已解决]尝试把Python版微信SDK wechat-python-sdk集成到Flask中

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.179 seconds, using 22.10MB memory