微信推送管理

我们可以通过微信的公众平台 为我们用户推送消息,在用户访问我们网址时,我们可以为他绑定微信号,下次登陆就用这个微信号登陆

在使用之前我们先了解一下

大致流程

微信推送管理

点击获取绑定按钮操作

大致操作

1.在微信公网地址上拼接我们的商户 回调地址   本地随机用户ID

2.把地址交给前端,前端渲染二维码

 

@auth
def bind_qcode(request):
    """
    生成二维码
    :param request: 
    :return: 
    """
    ret = {'code': 1000}
    try:
        # 生成一个地址
        access_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={redirect_uri}&response_type=code&scope=snsapi_userinfo&state={state}#wechat_redirect"
        access_url = access_url.format(
            # 商户的appid
            appid=settings.WECHAT_CONFIG["app_id"], # 'wx6edde7a6a97e4fcd',
            # 回调地址
            redirect_uri=settings.WECHAT_CONFIG["redirect_uri"],
            # 当前登录用户的唯一id,与第三方平台交互的用户唯一id
            state=request.session['user_info']['uid'] # 为当前用户生成MD5值
        )
        ret['data'] = access_url
    except Exception as e:
        ret['code'] = 1001
        ret['msg'] = str(e)

    return JsonResponse(ret)

用户扫码后 微信get请求我们提供url

我们可以通过get 请求得到的code 和state

向微信公网2发送get (需要传递app app** code 和唯一字符串"grant_type": 'authorization_code',)

通过返回的结果 拿到用户id 然后绑定

def callback(request):
    """
    用户在手机微信上扫码后,微信自动调用该方法。
    用于获取扫码用户的唯一ID,以后用于给他推送消息。
    :param request: 
    :return: 
    """
    code = request.GET.get("code")

    # 用户md5值,用户唯一id
    state = request.GET.get("state")
    print(code)

    # 获取该用户openId(用户唯一,用于给用户发送消息)
    # request模块朝https://api.weixin.qq.com/sns/oauth2/access_token地址发get请求
    res = requests.get(
        url="https://api.weixin.qq.com/sns/oauth2/access_token",
        params={
            "appid": settings.WECHAT_CONFIG["app_id"],
            "secret": settings.WECHAT_CONFIG["appsecret"],
            "code": code,
            "grant_type": 'authorization_code',
        }
    ).json()
    # res.data   是json格式
    # res=json.loads(res.data)
    # res是一个字典
    # 获取的到openid表示用户授权成功
    openid = res.get("openid")
    if openid:
        models.UserInfo.objects.filter(uid=state).update(wx_id=openid)
        response = "<h1>授权成功 %s </h1>" % openid
    else:
        response = "<h1>用户扫码之后,手机上的提示</h1>"
    return HttpResponse(response)

 

为用户推送消息

商户登陆方法 拿到token 和 用户id

调用 send_custom_msg方法

  发送post请求 把用户id和内容发送给微信服务器

得到结果  结果errocde ==0 就是发送成功

def sendmsg(request):
    def get_access_token():
        """
        获取微信全局接口的凭证(默认有效期俩个小时)
        如果不每天请求次数过多, 通过设置缓存即可
        """
        result = requests.get(
            url="https://api.weixin.qq.com/cgi-bin/token",
            params={
                "grant_type": "client_credential",
                "appid": settings.WECHAT_CONFIG['app_id'],
                "secret": settings.WECHAT_CONFIG['appsecret'],
            }
        ).json()
        return result.get("access_token",None)

    access_token = get_access_token()

    openid = models.UserInfo.objects.get(id=1).wx_id

    def send_custom_msg():
        body = {
            "touser": openid,
            "msgtype": "text",
            "text": {
                "content": 'lqz大帅哥'
            }
        }
        response = requests.post(
            url="https://api.weixin.qq.com/cgi-bin/message/custom/send",
            # 放到路径?后面的东西
            params={
                'access_token': access_token
            },
            # 这是post请求body体中的内容
            data=bytes(json.dumps(body, ensure_ascii=False), encoding='utf-8')
        )
        # 这里可根据回执code进行判定是否发送成功(也可以根据code根据错误信息)
        result = response.json()
        return result

    def send_template_msg():
        """
        发送模版消息
        """
        res = requests.post(
            url="https://api.weixin.qq.com/cgi-bin/message/template/send",
            params={
                'access_token': access_token
            },
            json={
                "touser": openid,
                "template_id": 'IaSe9s0rukUfKy4ZCbP4p7Hqbgp1L4hG6_EGobO2gMg',
                "data": {
                    "first": {
                        "value": "lqz",
                        "color": "#173177"
                    },
                    "keyword1": {
                        "value": "大帅哥",
                        "color": "#173177"
                    },
                }
            }
        )
        result = res.json()
        return result

    result = send_custom_msg()

    if result.get('errcode') == 0:
        return HttpResponse('发送成功')
    return HttpResponse('发送失败')