doraemonext / wechat-python-sdk Goto Github PK
View Code? Open in Web Editor NEW微信公众平台 Python 开发包 [DEPRECATED]
License: BSD 2-Clause "Simplified" License
微信公众平台 Python 开发包 [DEPRECATED]
License: BSD 2-Clause "Simplified" License
我用Flask开发了个微信公众号,实现了个答题抽奖活动,需要验证答题者是否已经订阅,主要流程如下:
为了方便描述,以下wechat实例为wechat-python-sdk提供的WechatBasic对象。
但是在access_token需要刷新时会碰到个问题:
由于Flask中我使用的wechat实例可能只能存活于一次session之中,所以每个用户的访问可能都会导致一次wechat实例初始化
证明过程是:我在wechat对象的构造函数中打印了log,每次网页请求都会打印一条log,所以证明了构造函数被调用
解决方法有两个:
第二个方法也有问题,在access_token即将过期时,
在进行问题描述的时候我突然想到,可以在进行access_token保存时验证expire时间,如果expire时间比数据库中时间要晚,则说明这个access_token是后刷新的,予以保存,否则丢弃。
I 160308 01:34:21 connectionpool:758] Starting new HTTPS connection (1): api.weixin.qq.com
[E 160308 01:34:22 web:1406] Uncaught exception POST /wechatcheck?signature=75e15237ad8c613306a3f36b7cade96b438d85aa×tamp=1457372062&nonce=826836284 (101.226.103.72)
HTTPServerRequest(protocol='https', host='app.tsingdata.com', method='POST', uri='/wechatcheck?signature=75e15237ad8c613306a3f36b7cade96b438d85aa×tamp=1457372062&nonce=826836284', version='HTTP/1.0', remote_ip='101.226.103.72', headers={'Content-Length': '274', 'X-Scheme': 'https', 'Host': 'app.tsingdata.com', 'Accept': '/', 'User-Agent': 'Mozilla/4.0', 'Connection': 'close', 'Pragma': 'no-cache', 'X-Real-Ip': '101.226.103.72', 'Content-Type': 'text/xml'})
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/tornado/web.py", line 1331, in _execute
result = method(_self.path_args, *_self.path_kwargs)
File "/var/marsapp/web/views/page.py", line 358, in post
response = self.process(wechat, body_text)
File "/var/marsapp/web/views/page.py", line 331, in process
self.report_msg(message, wechat)
File "/var/marsapp/web/views/page.py", line 305, in report_msg
user_info = wechat.get_user_info(str(message.source))
File "/usr/local/lib/python2.7/dist-packages/wechat_sdk/basic.py", line 533, in get_user_info
verify=False
File "/usr/local/lib/python2.7/dist-packages/wechat_sdk/lib/request.py", line 72, in get
*_kwargs
File "/usr/local/lib/python2.7/dist-packages/wechat_sdk/lib/request.py", line 30, in request
access_token = self.__conf.access_token if self.__conf is not None else access_token
File "/usr/local/lib/python2.7/dist-packages/wechat_sdk/core/conf.py", line 156, in access_token
self.grant_access_token() # 从腾讯服务器获取 access token 并更新
File "/usr/local/lib/python2.7/dist-packages/wechat_sdk/core/conf.py", line 208, in grant_access_token
access_token=self.__access_token
File "/usr/local/lib/python2.7/dist-packages/wechat_sdk/lib/request.py", line 72, in get
*_kwargs
File "/usr/local/lib/python2.7/dist-packages/wechat_sdk/lib/request.py", line 46, in request
*_kwargs
File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 53, in request
return session.request(method=method, url=url, *_kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 468, in request
resp = self.send(prep, *_send_kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 576, in send
r = adapter.send(request, *_kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/adapters.py", line 447, in send
raise SSLError(e, request=request)
SSLError: [Errno 1] _ssl.c:510: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
为什么会出现这个问题?是因为我的网站使用的是HTTPS,然后跟微信之间校验CA证书有问题么?应该怎么处理?谢谢!
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
转发到多客服的消息类型:transfer_customer_service
以及其他微信客服功能的 API
你好,我想问下非官方接口中发消息的用户的fakeid是怎么获取的?
现在 如果用 pip3 install wechat-sdk
的话获取的 v0.5.9 会有来自 StringIO 的 ImportError,看了一下源码发现已经修复了,希望 release 一下,方便直接通过包管理器安装
命令:pip install --upgrade wechat-sdk
前提:系统是CentOS6.4 已经安装了0.4.0版本的wechat-sdk
结果:
执行过程中显示
Downloading/unpacking wechat-sdk from https://pypi.python.org/packages/source/w/wechat-sdk/wechat-sdk-0.4.1.tar.gz#md5=a9483d383bfab3bc07b91e22645340c1
Running setup.py egg_info for package wechat-sdk
Requirement already up-to-date: requests==2.3.0 in /usr/lib/python2.6/site-packages (from wechat-sdk)
Installing collected packages: wechat-sdk
Found existing installation: wechat-sdk 0.4.0
Uninstalling wechat-sdk:
Successfully uninstalled wechat-sdk
Running setup.py install for wechat-sdk
Successfully installed wechat-sdk
但执行结束后使用pip list
查看版本,显示的版本还是0.4.0。
注:直接下载源码python setup.py install可以升级成功
为了帮助公众号实现灵活的业务运营,微信公众平台新增了个性化菜单接口,开发者可以通过该接口,让公众号的不同用户群体看到不一样的自定义菜单。该接口开放给已认证订阅号和已认证服务号。
http://mp.weixin.qq.com/wiki/0/c48ccd12b69ae023159b4bfaa7c39c20.html
场景:用户发送任意文本, 服务器原样返回
环境:python 2.7.11 + Flask
在加密模式下, 发送字符或数字,回复正确,发送中文时,出现错误:该公众号暂时无法提供服务,请稍后再试
部分测试代码如下:
content = u'你好'
content = content.decode('utf-8') if not isinstance(content, unicode) else content
return wechat.response_text(content)
当使用明文模式时, 发送中文,回复正常
错误如下:
`
Collecting wechat-python-sdk
Downloading wechat-python-sdk-0.6.1.tar.gz (61kB)
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\igice\AppData\Local\Temp\pycharm-packaging\wechat-python-sdk\setup.py", line 11, in
long_description=open("README.rst").read(),
UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 2: illegal multibyte sequence
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\igice\AppData\Local\Temp\pycharm-packaging\wechat-python-sdk
`
ERROR | Internal Server Error: /wx/portal/
Traceback (most recent call last):
File "/home/jezhang/djangocms/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
response = callback(request, _callback_args, *_callback_kwargs)
File "/home/jezhang/djangocms/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 77, in wrapped_view
return view_func(_args, *_kwargs)
File "./weixin/views.py", line 211, in portal
user_json = wechat.get_user_info(wx_openid,lang='zh_CN')
File "./wechat_sdk/basic.py", line 547, in get_user_info
'lang': lang,
File "./wechat_sdk/basic.py", line 937, in _get
**kwargs
File "./wechat_sdk/basic.py", line 921, in _request
r.raise_for_status()
File "/home/jezhang/djangocms/lib/python2.7/site-packages/requests/models.py", line 831, in raise_for_status
raise HTTPError(http_error_msg, response=self)
HTTPError: 561 Server Error: FastReject
请问 @doraemonext 是否有计划增加对微信企业号的支持?
我看到wechatpy已经支持了企业号,但是个人感觉wechat-python-sdk的设计和使用上比wechatpy优雅很多,所以希望做企业号也能继续沿用wechat-python-sdk的风格。
谢谢!
readme.rst里有编码错误,在各种环境下均无法成功安装。当把setup中的长描述字段改为固定字符串时一切正常。
最近在用Python开发微信公共账号服务器,使用的是apache+mod_perl
和你提供的wechat-python-sdk,但是只要我导入你的包就会报下面的错误
AH00052: child pid 32475 exit signal Segmentation fault
我用的是下面的方式导入
from wechat_sdk import WechatBasic
系统:Linux 2.6.32-431.20.3.el6.x86_64(CentOS 6.5 64位,放在阿里云上)
apache:Server version: Apache/2.4.10 (Unix) (编译安装)
./configure --prefix=/usr/local/apache2
mod_python:mod-python (3.5.0-)(编译安装)
./configure --with-apxs=/usr/local/apache2/bin/apxs --with-python=/usr/bin/python2
python:系统自带的版本 Python 2.6.6 (r266:84292)
wechat-python-sdk:wechat-sdk (0.4.0)
conf = WechatConf( token='weixin', appid='wx0ec87cb12131239be97', appsecret='a4c6c140f7345bb32174a4e86581212', encrypt_mode='safe', encoding_aes_key='L6ITjVvks1X4Y0TUeQ2mcotZY0L1mFYW5lqxF2ZzYDp', access_token='6Z8Yqhc1GTABYkBFUT4R1lSwwzf4RQ_HBrfXa8l3lhJ4nIrqOrycscxow5FFvm6_oyeOwNAyK3Hf4NfP0vM-VUTkABocLF0KwyWZYVOIVUV22UjWRF1P50cOsN_Kxpl8CUReAEAUMJ', access_token_expires_at=1454668255,) conf.get_jsapi_ticket()
一直得到的是41001错误
发现每次发送一条消息就要消耗一次获取access_token权限,由于获取access_token只有十万次,对于访问量较多的订阅号不划算,我可以自己存储自己的access_token,建议在发送消息时新增一个参数用于传递access_tokne
recently after i registered a new weixin-mp account, it required me to generate encodingAESKey.
so i wonder whether this sdk support that?
比如统一下单接口之类,似乎并没有开发
有没计划支持?
不知道作者在python3下的测试做的怎么样了,我在python3下使用遇到的主要问题还是编码格式的问题:
type(u'abc') == unicode # python2
type(b'abc') == str # python2
type(u'abc') == str # python3
type(b'abc') == bytes # python3
所以在一些编码判断和转码的地方都要做修改,比如WechatBasic.parse_data()和WechatBasic._transcoding()...
https://github.com/doraemonext/wechat-python-sdk/blob/master/wechat_sdk/basic.py#L289
这里直接使用 access_token 就可以了,本来 access_token 就会去判断刷新。
sdk里是不是没有提供被动回复空消息的函数?
官方文档:
假如服务器无法保证在五秒内处理并回复,必须做出下述回复,这样微信服务器才不会对此作任何处理,并且不会发起重试(这种情况下,可以使用客服消息接口进行异步回复),否则,将出现严重的错误提示。详见下面说明:
- 1、(推荐方式)直接回复success
- 2、直接回复空串(指字节长度为0的空字符串,而不是XML结构体中content字段的内容为空)
企业号有做的打算不?
add_news()函数只支持含有一张图片的图文消息吗?
正常的图文消息就像一篇文章似的呢? 可以图文交替出现。
如题
Collecting wechat-sdk
Using cached wechat-sdk-0.6.3.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\yk100\AppData\Local\Temp\pip-build-2im9121z\wechat-sdk\setup.py", line 11, in
long_description=open("README.rst").read(),
UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 2: illegal multibyte sequence
----------------------------------------
例如在upload_media 和 download_media 方法新增一个参数,以判断是临时素材还是永久素材,并根据此参数决定所请求的url
conf.set_appid_appsecret('oadjfadofa', 'adsfpijoasdf')
在胡乱给WechatConf实例配置appid和appsecret后,conf.access_token
依然能拿到原有的access_token。
支持python3吗?我用python3 执行from wechat_sdk import WechatBasic会报错
ImportError: cannot import name 'WechatBasic'
我搜了一下工程貌似没发现有这个接口可以用,可否考虑加入
mo-微笑 -> 😁
我的是python3 用pip安装提示 求解
Collecting wechat-sdk
Using cached wechat-sdk-0.5.8.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 20, in
File "C:\Users\n3292\AppData\Local\Temp\pip-build-yyhw7zno\wechat-sdk\setup.py", line 11, in
long_description=open("README.rst").read(),
UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 2: illegal multibyte sequence
如果已关注用户扫描带参数的二维码会触发SCAN事件,微信文档没写,但是实际遇到:
<xml>
<ToUserName><![CDATA[*****]]></ToUserName>
<FromUserName><![CDATA[*****]]></FromUserName>
<CreateTime>1415768788</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[SCAN]]></Event>
<EventKey><![CDATA[324234]]></EventKey>
<Ticket><![CDATA[*****]]></Ticket>
</xml>
能否在用户刚关注公众号时及时获取到其fakeid?
from wechat_sdk import WechatExt
wechat = WechatExt(username='USERNAME', password='PASSWORD', ifencodepwd=True)
wechat.send_message('FAKEID', 'text')
Traceback (most recent call last):
File "test_sendmessage.py", line 4, in
wechat.send_message('FAKEID', 'text')
File "C:\z\wechat_sdk\ext.py", line 165, in send_message
raise NeedLoginError(r.text)
wechat_sdk.exceptions.NeedLoginError: {"base_resp":{"ret":200002,"err_msg":"invalid args"}}
File "/home/wechat_sdk/basic.py", line 883, in _check_official_error
raise OfficialAPIError("{}: {}".format(json_data["errcode"], json_data["errmsg"]))
OfficialAPIError: 40001: invalid credential, access_token is invalid or not latest hint: [9.ZaUa0975vr21]
自从升级sdk后,间接性的出现40001错误,请问如何解决?
Hi, I am a beginner of python. When I use Send_message it raise NeedLoginError, then I put login before this function. But there is still a login error. My code shows as below. Could you please kindly help to fix it?
import json
from wechat_sdk import ext
loginname = '[email protected]'
loginname = loginname.encode()
loginpwd = 'j-------i'
loginpwd = loginpwd.encode()
wechat = ext.WechatExt (username = loginname ,password= loginpwd)
wechat.login()
username = "someone"
username = username.encode()
content = "testing msg"
content = content.encode()
wechat.send_message(username, content)
Result:NeedLoginError: {"base_resp":{"ret":200002,"err_msg":"invalid args"}}
Thank you!
验证方法中 self._check_token(),用途和用法请求解释一下!
{"base_resp":{"ret":10706,"err_msg":"customer block"}}
返回这个错误,用户48小时内没有和公众号互动就没法给用户发送信息,是不是得该一下啊
好可惜……
请问sdk内有没有网页授权的方法?
执行这句:wechat.parse_data(request.get_data())
request对象是flask提供的
大多数情况下都是正常的,但偶尔会看到日志里之行这一句会出现如下异常:
File "./app/weixin/views.py", line 65, in check
wechat.parse_data(request.get_data())
File "/usr/local/lib/python2.7/site-packages/wechat_sdk/basic.py", line 150, in parse_data
data = data.encode('utf-8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 218: ordinal not in range(128)
请问我需要如何处理呢?谢谢。
非常感谢你的项目,可以节省许多处理与微信接口连接的工作。
在开发中发现,python3版本的代码在处理加密的消息接口时,返回消息被微信服务器解析失败。经过与官方sample比对,发现问题可能出在加密前的字符串拼接上,python2与python3的len函数返回值不同造成的。
我暂时将 encrypt方法中struct.pack('I', socket.htonl(len(text))) 变更为 struct.pack('I', socket.htonl(len(text.encode())))后程序可以正常执行了。
期待你有更好的解决方案。
请基于wechat-python-sdk提供一个实例教程,尤其是基于我们这些初学者,没有实例不知道如何使用。
上传voice的时候,磁盘上的文件名为如果不为amr后缀 也是会报错(看后缀可能MP3也可以)。
感觉是少了Content-Type和filename
http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file
Content-Type用微信的测试工具看了一下
image应该是:image/jpeg
voice应该是:voice/amr
requests==2.3.0
调用:wechat.parse_data(req_body)
log:child pid 22284 exit signal Segmentation fault (11)
环境配置:和issue2一样
wechat-sdk版本:0.4.1
是不是和issue2有些关系?
微信的网页授权获取用户基本信息接口使用获取用户信息的,accesstoken的url和现在库里面的不同,是否添加sns的支持??
这个SDK只支持Python2吗?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.