python 自定义微信公众号 (wechat-sdk)

背景:python3.6,django
安装wechat-sdk,windows下安装不成功的可以参考这个python在windows下安装wechat-sdk
在公众号的基本配置中,要开启开发者密码,且要做好记录,如果用的地方超过两个,重置将会很麻烦
添加ip白名单,接下来填写服务器配置,此信息需要发送到服务器资源,url接口只支持80或443端口,且填写的url要能响应微信发送的token验证,请求为get请求,携带参数

?signature=a4faee3e0b3d0d4dbdbf562658419bd7025bf2f3&timestamp=1559813415&nonce=2078902341&openid=oGoEL6LW5vchtIZcgSAlOZrPPuFQ

signature:微信加密签名;
timestamp:时间戳;
nonce:随机数;
echostr:随机字符串
通过检验signature对请求进行校验。若确认此次GET请求来自微信服务器,原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败,代码如下方所示
校验成功后,可自定义菜单,可参考:微信公众平台自定义菜单

from xml.etree import ElementTree
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from wechat_sdk import WechatConf
from wechat_sdk import WechatBasic
from wechat_sdk.messages import TextMessage, ImageMessage, VoiceMessage, VideoMessage
# from wechat_sdk.exceptions import ParseError
from wechat_sdk.messages import EventMessage

conf = WechatConf(
    token='xxx', 		#自定义的token
    appid='wxxxxxxxxxx',		# 公众号的appid
    appsecret='xxxxxxxxxxxxxxxxx',		# 公众号的secret
    encrypt_mode='normal',)
wechat = WechatBasic(conf=conf)

@csrf_exempt
def check(request):
    if request.method == "GET":		
    # 用于在微信基本配置的服务器配置中,响应微信发送的Token验证
        try:
            signature = request.GET.get("signature")
            if signature:
                timestamp = request.GET.get("timestamp")
                nonce = request.GET.get("nonce")
                echostr = request.GET.get("echostr")
                if wechat.check_signature(signature, timestamp, nonce):
                    return HttpResponse(echostr)
            return HttpResponse(u"微信验证失败")

    except Exception as e:
        return HttpResponse(e)
else:
    menu = {											# 根据自己需求定义
            'button': [
                {
                    "name": "服务",
                    "sub_button": [
                        {
                            "type": "view",
                            "name": "规划",
                            "url": "https://xxx.com"		
                        },
                    ],
                },
                {
                    "name": "分类",
                    "sub_button": [
                        {
                            "type": "view",
                            "name": "精选",
                            "url": "http://www.xxx.com"
                        },
                    ],

                },
                {
                    "name": "加入",
                    "sub_button": [
                        {
                            "type": "media_id",
                            "name": "图片",
                            "media_id": "xxxxxxxxxxx"		# 获取的素材的media_id
                        },
                    ]
                },
            ]
            }
    try:
        # wechat.create_menu(menu)		# 创建菜单,创建完成可以注释掉,每次请求都创建会浪费接口调用次数
        wechat.parse_data(request.body)
        if isinstance(wechat.message, TextMessage):
            content = wechat.message.content
            print('content:', content)
            if wechat.message.content == "问卷":
                content = "参与 \n--> <a href='https://xxx.com/xxxt'>戳此进入</a>"
            else:
                content = "欢迎来到公众号^_^!"
            xml = wechat.response_text(content=content)
            return HttpResponse(xml, content_type="application/xml")
        elif isinstance(wechat.message, ImageMessage):
            picurl = wechat.message.picurl
            media_id = wechat.message.media_id
            xml = wechat.response_image(media_id=media_id)
            return HttpResponse(xml, content_type="application/xml")
        elif isinstance(wechat.message, VoiceMessage):
            media_id = wechat.message.media_id
            format = wechat.message.format
            recognition = wechat.message.recognition
            xml = wechat.response_voice(media_id=media_id)
            return HttpResponse(xml, content_type="application/xml")
        elif isinstance(wechat.message, VideoMessage):
            media_id = wechat.message.media_id
            xml = wechat.response_video(media_id=media_id)
            return HttpResponse(xml, content_type="application/xml")
        elif isinstance(wechat.message, EventMessage):
            if wechat.message.type == 'subscribe':  # 关注事件(包括普通关注事件和扫描二维码造成的关注事件)
                root = ElementTree.fromstring(request.body)
                print('root:', root)
                from_user = root.findtext(".//FromUserName")
                print('fromUser:', from_user)		# 此时可以获取到针对该公众号而言的用户的openid,自行添加逻辑即可
                xml = wechat.response_text(content="欢迎关注")
                return HttpResponse(xml, content_type="application/xml")

    except Exception as e:
        print(e)
    return HttpResponse(u"这是首页")

比技术文档操作起来简单多了,一切归功于wechat-sdk ,嘻嘻

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值