首页 > 编程 > Python > 正文

Python开发微信公众平台的方法详解【基于weixin-knife】

2020-02-16 01:49:43
字体:
来源:转载
供稿:网友

本文实例讲述了Python开发微信公众平台的方法。分享给大家供大家参考,具体如下:

这两天将之前基于微信公众平台的代码重构了下,基础功能以库的方式提供,提供了demo使用的是django,看着之前为赶进度写的代码真的惨不忍睹,所以weixin-knife产生了,正如其名,提供的是必要的功能,而不是完整的应用。weixin-knife可以很方便的处理关注,取关注事件,处理文本消息,回复用户信息,jssdk处理,oauth认证,以及微信支付。

github地址:https://github.com/Skycrab/weixin-knife。

首先看看怎么用

from .weixin import handler as HD@HD.subscribedef subscribe(xml):  return "welcome to brain"@HD.unsubscribedef subscribe(xml):  print "leave"  return "leave brain"

上面处理了关注和取关事件,通过装饰器处理的还算透明。

处理文本消息,回复图文消息如下:

@HD.textdef text(xml):  content = xml.Content  if content == "111":    return {"Title":"美女", "Description":"比基尼美女", "PicUrl":"http://9smv.com/static/mm/uploads/150411/2-150411115450247.jpg", "Url":"http://9smv.com/beauty/list?category=5"}  elif content == "222":    return [      ["比基尼美女", "比基尼美女", "http://9smv.com/static/mm/uploads/150411/2-150411115450247.jpg", "http://9smv.com/beauty/list?category=5"],      ["长腿美女", "长腿美女", "http://9smv.com/static/mm/uploads/150506/2-150506111A9648.jpg", "http://9smv.com/beauty/list?category=8"]    ]  elif content == "push":    Helper.send_text_message(xml.FromUserName, "推送消息测试")    return "push ok"  return "hello world"

如何文本是111或222,我们回复图文消息,如何使push,我们使用客服接口推送消息,其它返回“hello world"

一般我们会使用oauth网页授权获取用户的openid,如果是多个链接都需要通过oauth处理,代码会很难看,通过装饰器可以很好的处理这个问题。

def sns_userinfo_callback(callback=None):  """网页授权获取用户信息装饰器  callback(openid, userinfo):    return user  """  def wrap(func):    @wraps(func)    def inner(*args, **kwargs):      request = args[0] #django第一个参数request      openid = request.COOKIES.get('openid')      userinfo = None      if not openid:        code = request.GET.get("code")        if not code:          current = "http://"+ request.get_host() + request.get_full_path()          return redirect(WeixinHelper.oauth2(current))        else:          data = json.loads(WeixinHelper.getAccessTokenByCode(code))          access_token, openid, refresh_token = data["access_token"], data["openid"], data["refresh_token"]          #WeixinHelper.refreshAccessToken(refresh_token)          userinfo = json.loads(WeixinHelper.getSnsapiUserInfo(access_token, openid))      else:        ok, openid = Helper.check_cookie(openid)        if not ok:          return redirect("/")      request.openid = openid      if callable(callback):        request.user = callback(openid, userinfo)      response = func(request)      return response    return inner  return wrapsns_userinfo = sns_userinfo_callback()            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表