其他分享
首页 > 其他分享> > 0032 微信开发(07 公众号自定义菜单)

0032 微信开发(07 公众号自定义菜单)

作者:互联网

  微信菜单分为自定义菜单和个性化菜单,所谓自定义菜单,是所有用户看到相同的菜单,而个性化菜单,则表示根据不同用户看到不同的菜单。或者相同的菜单,不同的用户使用不同的效果。

  微信个性化菜单包含于自定义菜单,是一种特殊的自定义菜单。

  编写自定义菜单,首先得要获取点击菜单后跳转的网址,点击菜单后,才能够确定跳转到哪个网页,而要跳转网页,必须经过微信网页授权。

  打开Applications/Wechat/views/Utils.py文件,之前已经在这个文件中写了一个get_WeChatClient函数,用于获取WeChatClient对象。

  再增加两个函数,用以获取授权后的跳转地址,Utils.py文件全部内容如下:

from redis import Redis
from wechatpy.session.redisstorage import RedisStorage
from GeneralTools import Constents
from wechatpy.client import WeChatClient
from wechatpy.oauth import WeChatOAuth


def get_WeChatClient():
    """
    获取WeChatClient对象
    :return:WeChatClient对象
    """

    redis_client = Redis.from_url(Constents.WECHATPY_ACCESS_TOKEN_CACHE)
    session_interface = RedisStorage(
        redis_client,
        prefix="wechatpy"
    )

    return WeChatClient(
        Constents.WECHAT_APPID,
        Constents.WECHAT_APPSECRET,
        session=session_interface
    )


def get_WeChatOAuth(redirect_uri, state='123', scope='snsapi_userinfo'):
    """
    获取WeChatOAuth对象
    :param redirect_uri: 授权后重定向的回调链接地址, 请使用 urlEncode 对链接进行处理
    :param scope:应用授权作用域,snsapi_base,snsapi_userinfo
    :param state:重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节
    :return: WeChatOAuth对象
    """

    return WeChatOAuth(
        app_id=Constents.WECHAT_APPID,
        secret=Constents.WECHAT_APPSECRET,
        redirect_uri=redirect_uri,
        scope=scope,
        state=state
    )


def get_authorize_url(redirect_uri, state):
    """
    获取授权跳转地址
    :return: authorize_url
    """

    wechatOAuth = get_WeChatOAuth(redirect_uri, state)
    return wechatOAuth.authorize_url

  自定义菜单包括创建自定义菜单,创建个性化菜单,查询自定义菜单,删除个性化菜单,删除自定义菜单几个接口。

  代码如下:

from rest_framework.views import APIView
import logging
from rest_framework.response import Response
from rest_framework import status
from coreapi import Field
from coreschema import String
from rest_framework.schemas import AutoSchema

from .Utils import get_WeChatClient
from .Utils import get_authorize_url
from GeneralTools import Constents

# 获取在配置文件中定义的logger,用来记录日志
logger = logging.getLogger('tongheng2')


class CreateWechatSelfMenu(APIView):
    schema = AutoSchema(manual_fields=[
        Field(name="tag_id", required=True, location="query", schema=String(description='标签id'))
    ])

    # http://127.0.0.1:8000/ThirdParts/wechatpyselfmenu/create/?tag_id=100
    @classmethod
    def get(cls, request):
        """
        创建自定义菜单,默认创建用户组菜单</br>
        GET /ThirdParts/wechatpyselfmenu/create/?tag_id=<标签id></br>
        """

        tag_id = request.query_params.get('tag_id')
        logger.info("tag_id:%s" % tag_id)

        authorize_url1 = get_authorize_url(Constents.USER_HOME_ADDRESS, tag_id + '_1')
        authorize_url2 = get_authorize_url(Constents.USER_HOME_ADDRESS, tag_id + '_2')
        authorize_url3 = get_authorize_url(Constents.USER_HOME_ADDRESS, tag_id + '_3')
        logger.info("authorize_url:%s" % authorize_url1)
        logger.info("authorize_url:%s" % authorize_url2)
        logger.info("authorize_url:%s" % authorize_url3)

        wechat_client = get_WeChatClient()
        wechat_client_menu = wechat_client.menu

        # 创建个性化菜单
        data = wechat_client_menu.create({
            "button": [
                {
                    "type": "view",
                    "name": "首页",
                    "url": authorize_url1
                },
                {
                    "type": "view",
                    "name": "我的咨询",
                    "url": authorize_url2
                },
                {
                    "type": "view",
                    "name": "个人中心",
                    "url": authorize_url3
                }
            ],
        })
        logger.info("data:%s" % data)

        return Response(data=data, status=status.HTTP_200_OK)


class CreateWechatSingleMenu(APIView):
    schema = AutoSchema(manual_fields=[
        Field(name="tag_id", required=True, location="query", schema=String(description='标签id'))
    ])

    @classmethod
    def get(cls, request):
        """
        创建个性化菜单</br>
        GET /ThirdParts/wechatpymenu/create/?tag_id=<标签id></br>
        """

        tag_id = request.query_params.get('tag_id')
        logger.info("tag_id:%s" % tag_id)

        authorize_url = Constents.USER_HOME_ADDRESS
        page1_caption = '父亲首页'
        page2_caption = '父亲询问'
        page3_caption = '父亲个人'
        if tag_id == '100':
            # 用户
            authorize_url = Constents.USER_HOME_ADDRESS
            page1_caption = '父亲首页'
            page2_caption = '父亲询问'
            page3_caption = '父亲个人'
        elif tag_id == '101':
            page1_caption = '儿子首页'
            page2_caption = '儿子询问'
            page3_caption = '儿子个人'
            authorize_url = Constents.USER_HOME_ADDRESS

        authorize_url1 = get_authorize_url(authorize_url, tag_id + '_1')
        authorize_url2 = get_authorize_url(authorize_url, tag_id + '_2')
        authorize_url3 = get_authorize_url(authorize_url, tag_id + '_3')
        logger.info("authorize_url:%s" % authorize_url1)
        logger.info("authorize_url:%s" % authorize_url2)
        logger.info("authorize_url:%s" % authorize_url3)

        wechat_client = get_WeChatClient()
        wechat_client_menu = wechat_client.menu

        # 创建个性化菜单
        data = wechat_client_menu.add_conditional({
            "button": [
                {
                    "type": "view",
                    "name": page1_caption,
                    "url": authorize_url1
                },
                {
                    "type": "view",
                    "name": page2_caption,
                    "url": authorize_url2
                },
                {
                    "type": "view",
                    "name": page3_caption,
                    "url": authorize_url3
                }
            ],
            "matchrule": {
                "tag_id": tag_id,  # 用户标签的id
                "sex": "",
                "country": "",
                "province": "",
                "city": "",
                "client_platform_type": "",
                "language": ""
            }
        })
        logger.info("data:%s" % data)

        return Response(data=data, status=status.HTTP_200_OK)


class SelectWechatMenu(APIView):

    # http://127.0.0.1:8000/ThirdParts/wechatpymenu/select/
    @classmethod
    def get(cls, request):
        """
        查询自定义菜单,个性化菜单也是一起查询出来</br>
        GET /ThirdParts/wechatpymenu/select/</br>
        """

        wechat_client = get_WeChatClient()
        wechat_client_menu = wechat_client.menu

        # 查询自定义菜单
        data = wechat_client_menu.get()
        logger.info("data:%s" % data)

        return Response(data=data, status=status.HTTP_200_OK)


class DeleteWechatSingleMenu(APIView):
    schema = AutoSchema(manual_fields=[
        Field(name="menu_id", required=True, location="query", schema=String(description='菜单ID'))
    ])

    # http://127.0.0.1:8000/ThirdParts/wechatpymenu/delete/?menu_id=434758783
    @classmethod
    def get(cls, request):
        """
        删除个性化菜单
        GET /ThirdParts/wechatpymenu/delete/?menu_id=<菜单ID>
        """

        menu_id = request.query_params.get('menu_id')
        logger.info("menu_id:%s" % menu_id)

        wechat_client = get_WeChatClient()
        wechat_client_menu = wechat_client.menu

        # 删除个性化菜单
        data = wechat_client_menu.del_conditional(menu_id)
        logger.info("data:%s" % data)

        return Response(data=data, status=status.HTTP_200_OK)


class DeleteWechatSelfMenu(APIView):

    # http://127.0.0.1:8000/ThirdParts/wechatpyselfmenu/delete/
    @classmethod
    def get(cls, request):
        """
        删除自定义菜单,使用自定义菜单删除接口会连带删除所有个性化菜单
        GET /ThirdParts/wechatpyselfmenu/delete/
        """

        wechat_client = get_WeChatClient()
        wechat_client_menu = wechat_client.menu

        # 删除自定义菜单
        data = wechat_client_menu.delete()
        logger.info("data:%s" % data)

        return Response(data=data, status=status.HTTP_200_OK)

  

标签:authorize,菜单,07,自定义,get,url,微信,data,id
来源: https://www.cnblogs.com/dorian/p/12392270.html