微信推送消息实战

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

# 微信网页授权地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842

第一步:获取认证信息、测试模板、等
  

       

   

第二步:后端代码:

  1.获取二维码网址:

  

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"],
            redirect_uri=settings.WECHAT_CONFIG["redirect_uri"],
            state=request.user.user_info.uid
            # state=request.session['user_info']['uid']
        )
        ret['data'] = access_url
    except Exception as e:
        ret['code'] = 1001
        ret['msg'] = str(e)

    return ret
生成二维码网址

  2.微信回调函数获取用户的微信ID:

  

def callback(request):
    """
    用户在手机微信上扫码后,微信自动调用该方法。
    用于获取扫码用户的唯一ID,以后用于给他推送消息。
    :param request:
    :return:
    """
    code = request.GET.get("code")
    # 用户UID
    state = request.GET.get("state")
    # 获取该用户openId(用户唯一,用于给用户发送消息)
    res = requests.get(
        url="https://api.weixin.qq.com/sns/oauth2/access_token",
        params={
            "appid": 'wxdcabfb8f65139bd1',
            "secret": '5336031fae415e05571431d985c63017',
            "code": code,
            "grant_type": 'authorization_code',
        }
    ).json()
    # 获取的到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'],
                "secret": settings.WECHAT_CONFIG['appsecret'],
            }
        ).json()
        if result.get("access_token"):
            access_token = result.get('access_token')
        else:
            access_token = None
        return access_token

    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": '要发送的内容...'
            }
        }
        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()
    print(result)
    if result.get('errcode') == 0:
        return HttpResponse('发送成功')
    return HttpResponse('发送失败')
微信ID和发送模板消息

第三步:前端绑定用户名和密码(Vue通过qrcodejs2生成绑定二维码)
  

<template>
    <div id="bindingweixin">
      <div>
        <h3>第一步:关注公众号</h3>
        <img src="static/imgs/weixin.jpg" alt="" height="200px" width="200px">
      </div>
      <div>
        <h3>第二步:生成二维码,扫描绑定</h3>
        <input type="button" value="点击生成绑定二维码" @click="getBindUserQcode">
        <div id="qrcode" style="width: 560px;height: 560px;background-color: white;"></div>
      </div>


    </div>
</template>

<script>
    import QRCode from 'qrcodejs2';
    import Cookie from 'vue-cookies';
    export default {
        name: "binding-weixin",
        data(){
          return{
            qrcode:''
          }
        },
        methods:{
          getBindUserQcode:function(){
            let csrftoken = Cookie.get('csrftoken');
            this.$axios.request({
              url:this.$store.state.apiList.bindingWeixin,
              method:'get',
              // params: {foo: 'bar'},
              headers: {"X-CSRFToken":csrftoken }
            }).then(res=>{
              this.qrcode.clear();
              this.qrcode.makeCode(res.data.data);
            }).catch(res=>{

            })
          }
        },
      mounted(){
                this.qrcode = new QRCode('qrcode',{
                text:'',
                width:200,
                height:200,
                colorDark:'#000000',
                colorLight:'#ffffff',
                correctLevel:3
                })
      }
    }
</script>

<style scoped>

</style>
Vue代码

猜你喜欢

转载自www.cnblogs.com/wuchenggong/p/9768025.html