qhfl-9 微信模板消息推送
生活随笔
收集整理的這篇文章主要介紹了
qhfl-9 微信模板消息推送
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
開發(fā)中用的是測試號
微信公眾號認證流程
用戶登陸
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><form action="/login/" method="post">{% csrf_token %}<input type="text" name="user" placeholder="用戶名"><input type="password" name="pwd" placeholder="密碼"><input type="submit" value="登錄"></form> </body> </html> login.html {% 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>請關(guān)注路飛學城服務號,并綁定個人用戶(用于以后的消息提醒)</h1><div><h3>第一步:關(guān)注路飛學城微信服務號</h3><img style="height: 100px;width: 100px" src="{% static "img/wx.png" %}"></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> 登陸成功后跳轉(zhuǎn)到頁面關(guān)注公眾號的
然后綁定權(quán)限
模板信息的新建
用戶登錄,
關(guān)注公眾號,刷二維碼或點擊鏈接(向微信服務器說授予某公眾號應用權(quán)限),微信服務器再通過二維碼里面回調(diào)url(綁定時里面鏈接或二維碼的重定向url),通知開發(fā)服務器,我們在通過微信服務區(qū)通知我們的url里面的code,請求獲取用戶的openid(即權(quán)限id)然后保存到數(shù)據(jù)庫。
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 # 沙箱環(huán)境地質(zhì):https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/logindef 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 innerdef login(request):"""用戶登錄:param request::return:"""# models.UserInfo.objects.create(username='wen',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):"""用戶登錄后,關(guān)注公眾號,并綁定個人微信(用于以后消息推送):param request::return:"""return render(request, 'bind.html')@auth def bind_qcode(request):"""生成二維碼 用戶點擊或掃描用于向微信服務器發(fā)送綁定某個微信公眾號的請求(用戶到微信服務器的公眾號處報到)鏈接里面會含有重定向的url,和從微信請求攜帶的code(用于重定向的url再次向微信服務器請求用戶openid):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.session['user_info']['uid'])ret['data'] = access_urlexcept Exception as e:ret['code'] = 1001ret['msg'] = str(e)return JsonResponse(ret)def callback(request):"""用戶在手機微信上掃碼后,微信自動調(diào)用該方法。 二維碼中含有重定向的url,用于獲取掃碼用戶的唯一ID,以后用于給他推送消息。:param request::return:"""code = request.GET.get("code") #像微信服務器要的code# 用戶UIDstate = request.GET.get("state")# 獲取該用戶openId(用戶唯一,用于給用戶發(fā)送消息)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()# 獲取的到openid表示用戶授權(quán)成功openid = res.get("openid")print("get ",openid)if openid:models.UserInfo.objects.filter(uid=state).update(wx_id=openid)response = "<h1>授權(quán)成功 %s </h1>" % openidelse:response = "<h1>用戶掃碼之后,手機上的提示</h1>"return HttpResponse(response)def sendmsg(request):def get_access_token():"""獲取微信全局接口的憑證(默認有效期倆個小時)如果不每天請求次數(shù)過多, 通過設置緩存即可"""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 = Nonereturn access_tokenaccess_token = get_access_token()print("---------",request.POST)# user_id = request.get()openid = models.UserInfo.objects.get(id=2).wx_id #獲取用戶id,而不是直接填一個數(shù)print("send msg",openid)# def send_custom_msg():# body = {# "touser": openid,# "msgtype": "text",# "text": {# "content": '要發(fā)送的內(nèi)容...'# }# }# 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')# )# # 這里可根據(jù)回執(zhí)code進行判定是否發(fā)送成功(也可以根據(jù)code根據(jù)錯誤信息)# result = response.json()# return resultdef send_template_msg():"""發(fā)送模版消息"""res = requests.post(url="https://api.weixin.qq.com/cgi-bin/message/template/send",params={'access_token': access_token},json={"touser": openid,"template_id": settings.WECHAT_CONFIG['template_id'],"data": {"key": {"DATA": "lalal","color": "#173177"},"value": {"DATA": "關(guān)注本公眾號","color": "#173177"},}})result = res.json()return resultresult = send_template_msg()print(result)if result.get('errcode') == 0:return HttpResponse('發(fā)送成功')return HttpResponse('發(fā)送失敗') 視圖邏輯總結(jié)
以上是生活随笔為你收集整理的qhfl-9 微信模板消息推送的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: qhfl-7 结算中心
- 下一篇: 第36-37 Tomcat SVN