Coder Social home page Coder Social logo

weixin-python's Introduction

微信SDK

提供微信登录,公众号管理,微信支付,微信消息的全套功能

文档目录

欢迎提交Pull requests

如果需要单独使用其中的某些模块,可以见文档目录的具体模块

如果需要组合在一起可以参考快速开始

目录

安装

使用pip

sudo pip install weixin-python

使用easy_install

sudo easy_install weixin-python

安装最新版本 pip3 install git+https://github.com/zwczou/weixin-python

当前版本v0.5.7

功能

  • 微信登录
  • 微信支付
  • 微信公众号
  • 微信消息

异常

父异常类名为 WeixinError 子异常类名分别为 WeixinLoginError WeixinPayError WeixinMPError WeixinMsgError

用法

参数

  • WEIXIN_TOKEN 必填,微信主动推送消息的TOKEN
  • WEIXIN_SENDER 选填,微信发送消息的发送者
  • WEIXIN_EXPIRES_IN 选填,微信推送消息的有效时间
  • WEIXIN_MCH_ID 必填,微信商户ID,纯数字
  • WEIXIN_MCH_KEY 必填,微信商户KEY
  • WEIXIN_NOTIFY_URL 必填,微信回调地址
  • WEIXIN_MCH_KEY_FILE 可选,如果需要用退款等需要证书的api,必选
  • WEIXIN_MCH_CERT_FILE 可选
  • WEIXIN_APP_ID 必填,微信公众号appid
  • WEIXIN_APP_SECRET 必填,微信公众号appkey

上面参数的必填都是根据具体开启的功能有关, 如果你只需要微信登录,就只要选择 WEIXIN_APP_ID WEIXIN_APP_SECRET

  • 微信消息

    • WEIXIN_TOKEN
    • WEIXIN_SENDER
    • WEIXIN_EXPIRES_IN
  • 微信登录

    • WEIXIN_APP_ID
    • WEIXIN_APP_SECRET
  • 微信公众平台

    • WEIXIN_APP_ID
    • WEIXIN_APP_SECRET
  • 微信支付

    • WEIXIN_APP_ID
    • WEIXIN_MCH_ID
    • WEIXIN_MCH_KEY
    • WEIXIN_NOTIFY_URL
    • WEIXIN_MCH_KEY_FILE
    • WEIXIN_MCH_CERT_FILE

初始化

如果使用flask

# -*- coding: utf-8 -*-


from datetime import datetime, timedelta
from flask import Flask, jsonify, request, url_for
from weixin import Weixin, WeixinError


app = Flask(__name__)
app.debug = True


# 具体导入配
# 根据需求导入仅供参考
app.config.from_object(dict(WEIXIN_APP_ID='', WEIXIN_APP_SECRET=''))


# 初始化微信
weixin = Weixin()
weixin.init_app(app)
# 或者
# weixin = Weixin(app)

如果不使用flask

# 根据需求导入仅供参考
config = dict(WEIXIN_APP_ID='', WEIXIN_APP_SECRET='')
weixin = Weixin(config)

微信消息

如果使用django,添加视图函数为

url(r'^/$', weixin.django_view_func(), name='index'),

如果为flask,添加视图函数为

app.add_url_rule("/", view_func=weixin.view_func)
@weixin.all
def all(**kwargs):
	"""
	监听所有没有更特殊的事件
	"""
    return weixin.reply(kwargs['sender'], sender=kwargs['receiver'], content='all')


@weixin.text()
def hello(**kwargs):
	"""
	监听所有文本消息
	"""
    return "hello too"


@weixin.text("help")
def world(**kwargs):
	"""
	监听help消息
	"""
    return dict(content="hello world!")


@weixin.subscribe
def subscribe(**kwargs):
	"""
	监听订阅消息
	"""
    print kwargs
    return "欢迎订阅我们的公众号"

微信登录

@app.route("/login")
def login():
    """登录跳转地址"""
	openid = request.cookies.get("openid")
    next = request.args.get("next") or request.referrer or "/",
    if openid:
        return redirect(next)

    callback = url_for("authorized", next=next, _external=True)
    url = weixin.authorize(callback, "snsapi_base")
    return redirect(url)


@app.route("/authorized")
def authorized():
	"""登录回调函数"""
    code = request.args.get("code")
    if not code:
        return "ERR_INVALID_CODE", 400
    next = request.args.get("next", "/")
    data = weixin.access_token(code)
    openid = data.openid
    resp = redirect(next)
    expires = datetime.now() + timedelta(days=1)
    resp.set_cookie("openid", openid, expires=expires)
    return resp

微信支付

注意: 微信网页支付的timestamp参数必须为字符串



@app.route("/pay/jsapi")
def pay_jsapi():
	"""微信网页支付请求发起"""
	try:
        out_trade_no = weixin.nonce_str
        raw = weixin.jsapi(openid="openid", body=u"测试", out_trade_no=out_trade_no, total_fee=1)
        return jsonify(raw)
    except WeixinError, e:
        print e.message
        return e.message, 400


@app.route("/pay/notify, methods=['POST'])
def pay_notify():
    """
    微信异步通知
    """
    data = weixin.to_dict(request.data)
    if not weixin.check(data):
        return weixin.reply("签名验证失败", False)
    # 处理业务逻辑
    return weixin.reply("OK", True)


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=9900)

微信公众号

注意: 如果使用分布式,需要自己实现access_tokenjsapi_ticket函数

access_token默认保存在~/.access_token jsapi_ticket默认保存在~/.jsapi_ticket

默认在(HOME)目录下面,如果需要更改到指定的目录,可以导入库之后修改,如下

import weixin

DEFAULT_DIR = "/tmp"

获取公众号唯一凭证

weixin.access_token

获取ticket

weixin.jsapi_ticket

创建临时qrcode

data = weixin.qrcode_create(123, 30)
print weixin.qrcode_show(data.ticket)

创建永久性qrcode

# scene_id类型
weixin.qrcode_create_limit(123)
# scene_str类型
weixin.qrcode_create_limit("456")

长链接变短链接

weixin.shorturl("http://example.com/test")

weixin-python's People

Contributors

1y1n avatar catroll avatar daghan avatar duzhipeng avatar flytrap avatar fushengliangnian avatar lemon080910 avatar macuilxochitl avatar movingheart avatar pescn avatar sazima avatar stone-py avatar supperexception avatar wiilz avatar yihuaxiang avatar zaczwc avatar zwczou avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

weixin-python's Issues

python3中没有basestring

环境:python3.7
微信消息推送出现
NameError: name 'basestring' is not defined

我目前解决方案是在msg.py 内添加了一行

basestring = (str, bytes)

Python3 support?

安装的时候出现了错误,但是安装上了。

···
Running setup.py install for weixin-python
File ".../python3.4/site-packages/weixin/pay.py", line 89
except urllib2.HTTPError, e:
^
SyntaxError: invalid syntax
···

使用的时候出现了下面的错误:
···
from weixin.login import WeixinLogin
File ".../python3.4/site-packages/weixin/init.py", line 6, in
from msg import WeixinMsg
ImportError: No module named 'msg'
···
有支持Python 3的盼头么?

Django2.1 不兼容

问题挺多的。
先是django_view_func方法里还在用flask的获取参数方法
我改掉后收到文本消息回复时会提示:

reply: hello too
Internal Server Error: /weixin/
Traceback (most recent call last):
  File "/usr/share/zhibiyanjiusuo/zhiyansuo_beta/lib64/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/usr/share/zhibiyanjiusuo/zhiyansuo_beta/lib64/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/share/zhibiyanjiusuo/zhiyansuo_beta/lib64/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "./openwx/__init__.py", line 85, in hackDjango
    return wx.django_view_func(wx,request)
  File "./openwx/__init__.py", line 81, in django_view_func
    return run(self,request)
  File "./openwx/__init__.py", line 73, in run
    content=text
TypeError: reply() got an unexpected keyword argument 'username'

msg.py中_registry属性报错

root@42b326c392a7:/app# python manage.py
Traceback (most recent call last):
  File "manage.py", line 3, in <module>
    from app import create_app, db
  File "/app/app/__init__.py", line 6, in <module>
    from .weixin import weixin
  File "/app/app/weixin.py", line 7, in <module>
    @weixin.all
  File "/usr/local/lib/python3.5/dist-packages/weixin/msg.py", line 196, in wrapper
    self.register(type, key, func)
  File "/usr/local/lib/python3.5/dist-packages/weixin/msg.py", line 190, in register
    self._registry.setdefault(type, dict())[key] = func
  File "/usr/local/lib/python3.5/dist-packages/weixin/msg.py", line 220, in __getattr__
    raise AttributeError('invalid attribute "' + key + '"')
AttributeError: invalid attribute "_registry"

请教一下收到文本 自动回复图文消息的问题

回复内容变成了

<xml><ToUserName><![CDATA[ou0MI53DizZvCYWE6N3lmOkN1jKc

是的,变成了一个纯文本的信息,内容还被截取了一截
我的代码如下:

# 微信公众平台消息
@msg.text()
def text_messages(**kwargs):
    """
    监听所有文本消息
    """
    print('\n**************\nfrom weixin:\n', kwargs,'**************\n\n')
    articles = [{
        'title':'测试消息',
        'description':'描述内容',
        'picurl':'http://design.xxx.com/img/weixin_pmg.png',
        'url':'http://xxx.com/pmg_unit/suite/1/unit/0/pick/895a'
    }]
    ret= msg.reply(kwargs['sender'],type="news", sender=kwargs['receiver'], articles=articles)
    print(ret)
    return ret

打印出来的ret是完成的xml字符串

<xml><ToUserName><![CDATA[ou0MI53DizZvCYWE6N3lmOkN1jKc]]></ToUserName><FromUserName><![CDATA[gh_411e765ff6e3]]></FromUserName><CreateTime>1549984263</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>1</ArticleCount><Articles><item><Title><![CDATA[测试消息]]></Title><Description><![CDATA[描述内容]]></Description><PicUrl><![CDATA[http://design.zhibiyanjiusuo.com/img/weixin_pmg.png]]></PicUrl><Url><![CDATA[http://zhibiyanjiusuo.com/pmg_unit/suite/1/unit/0/pick/895a]]></Url></item></Articles></xml>

微信退款报ssl的问题

请问大家也遇到这个问题吗
requests.exceptions.SSLError: HTTPSConnectionPool(host='api.mch.weixin.qq.com', port=443): Max retries exceeded with url: /secapi/pay/refund (Caused by SSLError(SSLError(336445449, '[SSL] PEM lib (_ssl.c:3337)'),))

AttributeError: invalid attribute "app_id"

按照教程来,配置完成后,调用接口报如下错误:

    raise AttributeError('invalid attribute "' + key + '"')
AttributeError: invalid attribute "app_id"

AttributeError: invalid attribute "notify_url"

File "/home/tzy/venvs/wxpay/lib/python2.7/site-packages/weixin/msg.py", line 216, in getattr
raise AttributeError('invalid attribute "' + key + '"')
AttributeError: invalid attribute "notify_url

请问这个问题怎么解决
python == 2.7.5
用的是flask框架
调用pay_jsapi接口时报错

文档错误

total_fee 从字面意思预计应该是总金额把,但是文档描述为"商品描述" 请大佬确认一下。

代码质量 Cookie:未设置HttpOnly标记

您好,我是奇虎360代码卫士团队的工作人员,在我们的开源项目检测中发现weixin-python存在代码质量 Cookie:未设置HttpOnly标记隐患,详细信息如下:
image
在weixin-python-dev/example/login.py文件 第38行 ,程序生成Cookie时,未设置HTTPOnly标记,存在安全风险。为Cookie设置HTTPOnly标记,浏览器将不允许客户端脚本访问Cookie,可有效缓解XSS漏洞造成的威胁。可以改成 resp.set_cookie("openid", openid, expires=expires,httponly=True)

微信退款报ConnectionError:500

weixin-python-0.5.4

支付正常。

申请退款错误:
2019-05-22 15:38:24,310 - _get_conn - DummyThread-17 - DEBUG - Resetting dropped connection: api.mch.weixin.qq.com
Traceback (most recent call last):
File "/home/flaskMatch/venv/lib/python3.6/site-packages/urllib3/connectionpool.py", line 601, in urlopen
chunked=chunked)
File "/home/flaskMatch/venv/lib/python3.6/site-packages/urllib3/connectionpool.py", line 387, in _make_request
six.raise_from(e, None)
File "", line 2, in raise_from
File "/home/flaskMatch/venv/lib/python3.6/site-packages/urllib3/connectionpool.py", line 383, in _make_request
httplib_response = conn.getresponse()
File "/usr/local/lib/python3.6/http/client.py", line 1331, in getresponse
response.begin()
File "/usr/local/lib/python3.6/http/client.py", line 297, in begin
version, status, reason = self._read_status()
File "/usr/local/lib/python3.6/http/client.py", line 266, in _read_status
raise RemoteDisconnected("Remote end closed connection without"
http.client.RemoteDisconnected: Remote end closed connection without response

File "/home/flaskMatch/app/refpaywx/controller.py", line 91, in refund_pay
total_fee=total_amount, refund_fee=total_amount)
File "/home/flaskMatch/venv/lib/python3.6/site-packages/weixin/pay.py", line 199, in refund
return self._fetch(url, data, True)
File "/home/flaskMatch/venv/lib/python3.6/site-packages/weixin/pay.py", line 91, in _fetch
resp = self.sess.post(url, data=self.to_xml(data), cert=(self.cert, self.key))
File "/home/flaskMatch/venv/lib/python3.6/site-packages/requests/sessions.py", line 555, in post
return self.request('POST', url, data=data, json=json, **kwargs)
File "/home/flaskMatch/venv/lib/python3.6/site-packages/requests/sessions.py", line 508, in request
resp = self.send(prep, **send_kwargs)
File "/home/flaskMatch/venv/lib/python3.6/site-packages/requests/sessions.py", line 618, in send
r = adapter.send(request, **kwargs)
File "/home/flaskMatch/venv/lib/python3.6/site-packages/requests/adapters.py", line 490, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))

state

在state如果放入url以完成回调,目前只支持在url中放一个参数,当2个参数时,当前程序无法解析,会被截断。

微信企业付款到零钱提示找不到方法pay_individual

查了下WeixinPay类没有这个方法,在最新的代码仓库里有这个方法,文档中也有,为什么pip安装后就没有了呢,我安装的是weixin-python==0.5.4,不知道是不是最新的

>>> dir(WeixinPay)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_fetch', 'check', 'close_order', 'download_bill', 'jsapi', 'nonce_str', 'order_query', 'refund', 'refund_query', 'remote_addr', 'reply', 'sign', 'to_dict', 'to_xml', 'unified_order']

你好,自定义菜单和消息有两个问题,请指教,python版本v3.6.2

你好,有两个问题,请指教,python版本v3.6.2

1.菜单为中文名字时候报错40033,英文则没有问题

image

2.关注公众号后报错
image

代码如下所示:
`from weixin import Weixin, WeixinError
app.config['WEIXIN_APP_ID'] = appglobal.config["WX_OPTION"]["APPID"]
app.config['WEIXIN_APP_SECRET'] = appglobal.config["WX_OPTION"]["APPSECRET"]
app.config['WEIXIN_SENDER'] = appglobal.config["WX_OPTION"]["WEIXIN_SENDER"]
app.config['WEIXIN_EXPIRES_IN'] = appglobal.config["WX_OPTION"]["WEIXIN_EXPIRES_IN"]
app.config['WEIXIN_TOKEN']=appglobal.config["WX_OPTION"]["WEIXIN_TOKEN"]
'''初始化微信'''
weixin = Weixin()
weixin.init_app(app)
app.add_url_rule("/", view_func=weixin.view_func)

'''创建菜单'''
data = [
{
"type": "view",
"name": "测试1",
"url": "http://www.baidu.com"
},
{
"type": "click",
"name": "测试2",
"key": "menu_bdtj"
}
]
weixin.mp.menu_create(data)

@weixin.all
def all(**kwargs):
"""
监听所有没有更特殊的事件
"""
return weixin.reply(kwargs['sender'], sender=kwargs['receiver'], content='all')

@weixin.text()
def hello(**kwargs):
"""
监听所有文本消息
"""
return "hello too"

@weixin.text("help")
def world(**kwargs):
"""
监听help消息
"""
return dict(content="hello world!")

@weixin.subscribe
def subscribe(**kwargs):
"""
监听订阅消息
"""
print(kwargs)
return "欢迎订阅我们的公众号"`

电脑网站支付

这个包开发得真好,很规范。但是不知道支不支持电脑网站(Pc电脑)支付?谢谢答复!

支付回调接口问题

./weixin/pay.py 78行content.encode("utf-8"),提示type没有encode属性,去掉.encode("utf-8")就正常了

encode编码问题

使用django2.1 微信支付异步通知传回的数据,调用to_dict方法时,调用了encode,python3.7会报错,我改成了decode后可以继续执行

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.