Django微信测试号自定义菜单的实现

  • 流程图(来自官方)
    在这里插入图片描述
    下面的例子菜单的类型为click和views类型:(还有许多类型,可以到官网看)注意加粗部分
    click:点击推事件用户点击click类型按钮后,微信服务器会通过消息接口推送消息类型为event的结构给开发者(参考消息接口指南),并且带上按钮中开发者填写的key值,开发者可以通过自定义的key值与用户进行交互
    view:跳转URL用户点击view类型按钮后,微信客户端将会打开开发者在按钮中填写的网页URL,可与网页授权获取用户基本信息接口结合,获得用户基本信息。
    自定义菜单介绍:
    https://developers.weixin.qq.com/doc/offiaccount/Custom_Menus/Creating_Custom-Defined_Menu.html
  • 代码实现

models层

import urllib3
class wechat(object):
    AppID = 'wx1200d8073fb4fd14'
    AppSecret = 'ce6c8d28e4466e5c4086128b825970fa'     
    @classmethod
    def createMenu(self):
       menu = {
            "button": [
                {
                    "type": "view",
                    "name": "首页",
                    "url": "跳转的链接"
                },
                {
                    "type": "view",
                    "name": "商品列表",
                    "url": "跳转的链接"
                },
                {
                    "name": "我的",
                    "sub_button": [
                        {
                            "type": "view",
                            "name": "登录",
                            "url": "跳转的链接"
                        },
                        {
                            "type": "click",
                            "name": "问候语",
                            "key": "hello"
                        }]
                }]
        }
        data = json.dumps(menu,ensure_ascii=False).encode('utf-8')#将menu转换为json格式
        http = urllib3.PoolManager()#创建一个连接池
        access_token=wechat.get_token()#得到 access_token
	#用post方法
        postcreateurl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s" % (access_token)
        r1 = http.request('POST', postcreateurl, body=data)
    @classmethod
    def get_token(self):
        '''
        获得token的函数,并把token存在文件夹中,因为它只能保存两个小时
        :return:access_token
        '''
        filePath=os.path.join(settings.BASE_DIR,"static/token.txt")
        if os.path.exists(filePath):
            mtime=os.path.getmtime(filePath)
            print("mtime",mtime)
            nowtime=datetime.now().timestamp()
            print(nowtime)
            if nowtime-mtime<7200:
                print("nowtime-mtime<7200")
                f=open(filePath,encoding='utf-8')
                token=f.read()
                return token
        print("不存在或者nowtime-mtime>7200")
        f = open(filePath, 'w+', encoding='utf-8')
        gettoken = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (wechat.AppID, wechat.AppSecret)
        http = urllib3.PoolManager()#创建一个连接池
        r = http.request('GET', gettoken)#调用pool方法resquest
        access_token = json.loads(r.data.decode())['access_token']#返回的是一个httpResponse类型的对象,中间的data是我们要的,转码之后再得到access_token
        f.write(access_token)
        return access_token

views层

def handle(request):
    if request.method=="GET":
        print("get")
        signature = request.GET.get("signature")
        timestamp = request.GET.get("timestamp")
        nonce = request.GET.get("nonce")
        echostr = request.GET.get("echostr")
        token = "wjl" #请按照公众平台官网\基本配置中信息填写
        list = [token, timestamp, nonce]
        print(list)
        list.sort()
        sha1code="".join(list).encode("utf-8")
        hashcode=hashlib.sha1(sha1code).hexdigest()
        print(hashcode,signature)
        if hashcode == signature:
            return HttpResponse(echostr)
        else:
            return HttpResponse("配置失败")
    else:
        Data=request.body.decode("utf-8")  #得到发送过来的xml文本并转码
        recMsg = ET.fromstring(Data)
        ToUserName= recMsg.find('FromUserName').text 
        FromUserName = recMsg.find('ToUserName').text  
        msg_type = recMsg.find('MsgType').text
        if msg_type == 'event':
            print("进入了event",recMsg.find('Event').text)
            envent = recMsg.find('Event').text
           EventKey=recMsg.find('EventKey').text
           if envent == 'CLICK' and EventKey == "hello":#自定义菜单的click事件
                content = "欢迎你呀"
                return HttpResponse(vxmodels.wechat.send(ToUserName, FromUserName, content))
       ```
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值