wwg945

微信关注流程图解

代码实现

# 根据url生成二维码$(\'#qrcode\').empty().qrcode({text: url});清空内容,生成二维码
# 登录及登陆后的响应就不写了
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=settings.WECHAT_CONFIG["app_id"], # APPid
            redirect_uri=settings.WECHAT_CONFIG["redirect_uri"], # 回调函数地址,公网地址
            state=request.session[\'user_info\'][\'uid\']  # uid是本地来标识用户的字段
        )
        ret[\'data\'] = access_url
    except Exception as e:
        ret[\'code\'] = 1001
        ret[\'msg\'] = str(e)
    # 将生成的url返回
    return JsonResponse(ret)

# 回调路由对应的函数
def callback(request):
    """
    用户在手机微信上扫码后,微信自动调用该方法。
    用于获取扫码用户的唯一ID,以后用于给他推送消息。
    :param request:
    :return:
    """
    code = request.GET.get("code")
    # 本地为用户生成的唯一标识UID
    state = request.GET.get("state")
    # 获取该用户openId(用户唯一,用于给用户发送消息)
    # 此次访问并互惠获得用户的微信号,需要携带code进行访问
    res = requests.get(
        url="https://api.weixin.qq.com/sns/oauth2/access_token",
        params={
            "appid": \'wx041e7cba98e72bca\', # 公众号appID
            "secret": \'c17dddc8dcbe6bf3c7d5410d569e5b63\', # 公众号appsecret
            "code": code,
            "grant_type": \'authorization_code\',
        }
    ).json()
    # 获取的到openid表示用户授权成功,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)

推送消息

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\'], # APPID
                "secret": settings.WECHAT_CONFIG[\'appsecret\'], # APPSECREET
            }
        ).json()
        if result.get("access_token"):
            access_token = result.get(\'access_token\')
        else:
            access_token = None
        return access_token

    # 获取token
    access_token = get_access_token()
    # 获取用户的微信ID
    openid = models.UserInfo.objects.get(id=1).wx_id

    # 发送普通消息
    def send_custom_msg():
        body = {
            "touser": openid,
            "msgtype": "text",
            "text": {
                "content": \'要发送的内容...\'
            }
        }
        response = requests.post(
            url="https://api.weixin.qq.com/cgi-bin/message/custom/send",
            params={
                \'access_token\': access_token
            },
            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": \'0XbLbuNkn3wPPAYRVXM-MZ0gU0tPvVbsjfc1qoSH6CM\',
                "data": {
                    "first": {
                        "value": "魏文刚",
                        "color": "#173177"
                    },
                    "keyword1": {
                        "value": "辣瓜皮",
                        "color": "#173177"
                    },
                }
            }
        )
        result = res.json()
        return result
    # 这是一个字典
    result = send_custom_msg()
    if result.get(\'errcode\') == 0:
        return HttpResponse(\'发送成功\')
    return HttpResponse(\'发送失败\')

沙箱环境下的配置

沙箱环境地质:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

下面的微信号就是我们要获得的东西

模板消息,以及上面代码中的模板内容

 网页服务-网页账号

 

 

分类:

技术点:

相关文章:

  • 2021-09-24
  • 2021-12-06
  • 2021-10-14
  • 2021-10-21
  • 2021-12-08
猜你喜欢
  • 2021-12-02
  • 2021-09-25
  • 2021-12-16
  • 1970-01-01
  • 2022-12-23
相关资源
相似解决方案