Package: python-wechat
安装使用pipsudo pip install python-wechat使用easy_installsudo easy_install python-wechat安装开发版本sudo pip install git+https://github.com/catroll/python-wechat@dev功能微信登陆微信支付微信公众号微信消息用法异常父异常类名为WechatError子异常类名分别为WechatAuthErrorWechatPayErrorWechatMPErrorWechatMsgError参数WEIXIN_TOKEN必填，微信主动推送消息的TOKENWEIXIN_SENDER选填，微信发送消息的发送者WEIXIN_EXPIRES_IN选填，微信推送消息的有效时间WEIXIN_MCH_ID必填，微信商户ID，纯数字WEIXIN_MCH_KEY必填，微信商户KEYWEIXIN_NOTIFY_URL必填，微信回调地址WEIXIN_MCH_KEY_FILE可选，如果需要用退款等需要证书的api，必选WEIXIN_MCH_CERT_FILE可选WEIXIN_APP_ID必填，微信公众号appidWEIXIN_APP_SECRET必填，微信公众号appkey上面参数的必填都是根据具体开启的功能有关,
如果你只需要微信登陆，就只要选择WEIXIN_APP_IDWEIXIN_APP_SECRET微信消息WEIXIN_TOKENWEIXIN_SENDERWEIXIN_EXPIRES_IN微信登陆WEIXIN_APP_IDWEIXIN_APP_SECRET微信公众平台WEIXIN_APP_IDWEIXIN_APP_SECRET微信支付WEIXIN_APP_IDWEIXIN_MCH_IDWEIXIN_MCH_KEYWEIXIN_NOTIFY_URLWEIXIN_MCH_KEY_FILEWEIXIN_MCH_CERT_FILE初始化如果使用flask# -*- coding: utf-8 -*-


from datetime import datetime, timedelta
from flask import Flask, jsonify, request, url_for
from wechat import Wechat, WechatError


app = Flask(__name__)
app.debug = True


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


# 初始化微信
wechat = Wechat()
wechat.init_app(app)
# 或者
# wechat = Wechat(app)如果不使用flask# 根据需求导入仅供参考
config = dict(WEIXIN_APP_ID='', WEIXIN_APP_SECRET='')
wechat = Wechat(config)微信消息如果使用django，添加视图函数为url(r'^/$', wechat.django_view_func(), name='index'),如果为flask，添加视图函数为app.add_url_rule("/", view_func=wechat.view_func)@wechat.all
def all(**kwargs):
    """
    监听所有没有更特殊的事件
    """
    return wechat.reply(kwargs['sender'], sender=kwargs['receiver'], content='all')


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


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


@wechat.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 = wechat.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 = wechat.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 = wechat.nonce_str
        raw = wechat.jsapi(openid="openid", body=u"测试", out_trade_no=out_trade_no, total_fee=1)
        return jsonify(raw)
    except WechatError, e:
        print e.message
        return e.message, 400


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


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=9900)微信公众号注意:
如果使用分布式，需要自己实现access_token跟jsapi_ticket函数access_token默认保存在~/.access_tokenjsapi_ticket默认保存在~/.jsapi_ticket默认在(HOME)目录下面，如果需要更改到指定的目录，可以导入库之后修改，如下import wechat

DEFAULT_DIR = "/tmp"获取公众号唯一凭证wechat.access_token获取ticketwechat.jsapi_ticket创建临时qrcodedata = wechat.qrcode_create(123, 30)
print wechat.qrcode_show(data.ticket)创建永久性qrcode# scene_id类型
wechat.qrcode_create_limit(123)
# scene_str类型
wechat.qrcode_create_limit("456")长链接变短链接wechat.shorturl("http://example.com/test")