微信消息推送
一、消息推送、公众号、服务号、企业号
- 微信消息推送(越往下权限越大)
- 公众号(每天可以发一篇文章,不能主动发消息,能回复;通过文章,吸引你)
- 已认证公众号
- 服务号(主动推送消息,通知你,eg:告诉你得每月账单,前提是先关注)
- 已认证服务号
- 企业号(不使用qq, 企业内部人员聊天,得花钱)
介绍:
https://open.weixin.qq.com/
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433401084
https://open.weixin.qq.com/cgi-bin/frame?t=home/web_tmpl&lang=zh_CN
微信api 网站应用开发,资源中心:公众账号,开发者文档
权限介绍:
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433401084
二、测试:微信认证得服务号
基于:微信认证服务号,主动推送微信消息。
前提:关注服务号
环境:沙箱环境
沙箱环境地址:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
微信扫一扫登录:
这个就是,微信发送消息,手机收到推送得消息得提示!!
三、总结
总结: # 沙箱环境地址:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login 1. 注册账号 appID:wx89085e915d351cae appsecret:64f87abfc664f1d4f11d0ac98b24c42d 网页授权获取用户基本信息:47.98.134.86 或 域名 2. 关注公众号(已认证的服务号) 3. 生成二维码,用户扫描; 将用户信息发送给微信,微信再将数据发送给设置redirect_uri地址(md5值) 4. 回调地址:47.98.134.86/callback/ - 授权 - 用户md5 - 获取wx_id 在数据库中更新设置:wx_id 5. 发送消息(模板消息) - wx_id - access_token(2小时有效期)
四、代码分析
1. 用户登录,账号,密码;
将id,name,uid(MD5得唯一标识)注册到session中,跳转到bind二维码页面
2. 关注公众号得二维码,微信就可以拿到wx_id,诱导用户,
扫描bind_qcode二维码(是个地址),微信规定得:地址里面包含(app_id,redirect_url,uid)
call_back(redirect_url)函数,用户扫描之后就会调用该方法,获取wx_id,存到数据库中,以便于给他推送消息。
3. call_back()函数中,获取用户得唯一ID,wx_id, openid = res.get("openid"),
uid用户得到用户,update更新数据库中用户得wx_id字段。----注:这是微信回调得函数,需要公网IP,使我们得到wx_id,存起来
4. 发消息:
可以发模板消息,也可以发消息内容
先得到access_token(2小时有效期),
发模板消息,调用模板id, 以及wx_id,就可以发送消息,关注该微信号得人,就会收到微信推送得消息。
import json import functools import requests from django.conf import settings from django.shortcuts import render, redirect, HttpResponse from django.http import JsonResponse from app01 import models # 沙箱环境地址:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login def index(request): obj = models.UserInfo.objects.get(id=1) return render(request,'index.html',{'obj':obj}) def auth(func): @functools.wraps(func) def inner(request, *args, **kwargs): user_info = request.session.get('user_info') if not user_info: return redirect('/login/') return func(request, *args, **kwargs) return inner def login(request): """ 用户登录 :param request: :return: """ # models.UserInfo.objects.create(username='luffy',password=123) if request.method == "POST": user = request.POST.get('user') pwd = request.POST.get('pwd') obj = models.UserInfo.objects.filter(username=user, password=pwd).first() if obj: request.session['user_info'] = {'id': obj.id, 'name': obj.username, 'uid': obj.uid} return redirect('/bind/') else: return render(request, 'login.html') @auth def bind(request): """ 用户登录后,关注公众号,并绑定个人微信(用于以后消息推送) :param request: :return: """ return render(request, 'bind.html') @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=settings.WECHAT_CONFIG["app_id"], # 'wx89085e915d351cae', redirect_uri=settings.WECHAT_CONFIG["redirect_uri"], # 'http://47.93.4.198/test/', 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) def callback(request): """ 用户在手机微信上扫码后,微信自动调用该方法。 用于获取扫码用户的唯一ID,以后用于给他推送消息。 :param request: :return: """ code = request.GET.get("code") # 用户md5值 state = request.GET.get("state") # 获取该用户openId(用户唯一,用于给用户发送消息) res = requests.get( url="https://api.weixin.qq.com/sns/oauth2/access_token", params={ "appid": 'wx2daf9797dd8c6ebe', "secret": '3071a78cf1ba73e711b8d63636406380', "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": '7NRsdPThxOTkdoOiYN1LPBm0D_eQeif_7Ph9nZisdic', "data": { "first": { "value": "小屁孩", "color": "#173177" }, "keyword1": { "value": "嘿嘿嘿", "color": "#173177" }, } } ) result = res.json() return result # result = send_template_msg() result = send_custom_msg() if result.get('errcode') == 0: return HttpResponse('发送成功') return HttpResponse('发送失败')
{% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div style="width: 600px;margin: 0 auto"> <h1>请关注路飞学城服务号,并绑定个人用户(用于以后的消息提醒)</h1> <div> <h3>第一步:关注路飞学城微信服务号</h3> <img style="height: 100px;width: 100px" src="{% static "img/luffy_me.jpeg" %}"> </div> <input type="button" value="下一步【获取绑定二维码】" onclick="getBindUserQcode()"> <div> <h3>第二步:绑定个人账户</h3> <div id="qrcode" style="width: 250px;height: 250px;background-color: white;margin: 100px auto;"></div> </div> </div> <script src="{% static "js/jquery.min.js" %}"></script> <script src="{% static "js/jquery.qrcode.min.js" %}"></script> <script src="{% static "js/qrcode.js" %}"></script> <script> function getBindUserQcode() { $.ajax({ url: '/bind_qcode/', type: 'GET', success: function (result) { console.log(result); $('#qrcode').empty().qrcode({text: result.data}); } }); } </script> </body> </html>
# settings.py
############# 微信 ############## WECHAT_CONFIG = { 'app_id': 'wx2daf9797dd8c6ebe', 'appsecret': '3071a78cf1ba73e711b8d63636406380', 'redirect_uri': 'http://10.0.0.200/callback/', # 'redirect_uri': 'http://47.98.134.86/callback/', }
# models.py import hashlib from django.db import models class UserInfo(models.Model): username = models.CharField("用户名", max_length=64, unique=True) password = models.CharField("密码", max_length=64) uid = models.CharField(verbose_name='个人唯一ID',max_length=64, unique=True) wx_id = models.CharField(verbose_name="微信ID", max_length=128, blank=True, null=True, db_index=True) def save(self, *args, **kwargs): # 创建用户时,为用户自动生成个人唯一ID if not self.pk: m = hashlib.md5() m.update(self.username.encode(encoding="utf-8")) self.uid = m.hexdigest() super(UserInfo, self).save(*args, **kwargs)