1. 程式人生 > >Django——微信訊息推送

Django——微信訊息推送

前言

微信公眾號的分類

  • 微信訊息推送
    • 公眾號
      • 已認證公眾號
      • 服務號
      • 已認證服務號
      • 企業號

基於:微信認證服務號 主動推送微信訊息。
前提:關注服務號
環境:沙箱環境

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

流程:

  1. 註冊開發者賬號

    獲得:appID、appsecret

    網頁授權獲取使用者基本資訊:47.98.134.86 或 域名

  2. 關注公眾號(已認證的服務號)

    iHwTKA.png

  3. 生成二維碼,使用者掃描;
    將使用者資訊傳送給微信,微信再將資料傳送給設定redirect_uri地址(md5值)

    iH09rn.png

  4. 回撥地址:47.98.134.86/callback/

    iHfnQP.png

    • 授權
    • 使用者md5
    • 獲取wx_id
      在資料庫中更新設定:wx_id
  5. 傳送訊息(模板訊息)

    • wx_id

    • access_token(2小時有效期)

      iHfZRI.png

核心程式碼

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)

settings.py

WECHAT_CONFIG = {
    'app_id': 'wx3d0d44e8d59b5b8c',
    'appsecret': 'a4ede68946e9a2e7e36480d23865a64d',
    'redirect_uri': 'http://47.106.237.76/callback/',
}

views.py

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(to='/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": settings.WECHAT_CONFIG['app_id'],
            "secret": settings.WECHAT_CONFIG['appsecret'],
            "code": code,
            "grant_type": 'authorization_code',
        }
    ).json()
    # 獲取的到openid表示使用者授權成功
    openid = res.get("openid")
    print(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
    print(openid)

    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": 'NcN_W_aEIwu-FHyJx8djU99Z70AvwwGcEufXiTzj-NM',
                "data": {
                    "first": {
                        "value": "冰姐",
                        "color": "#173177"
                    },
                    "keyword1": {
                        "value": "美女",
                        "color": "#173177"
                    },
                }
            }
        )
        result = res.json()
        return result
    # 在這裡編輯要傳送的函式中的內容
    result = send_template_msg()

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



功能演示

1登陸:

iHwYBq.png

2客戶掃碼關注我們的公眾號

iHwTKA.png

為了獲得使用者的微信ID,我們需要客戶再次掃碼,向微信授權把ID給我們

iH09rn.png