第一步 :先进入微信测试公众号页面
然后是手机微信扫码授权后,就有如下界面
第二步 :配置接口信息
这一步可以参照微信接入说明 ,该页提供一个python的实例下载,很简单基本上修改一下自定义的TOKEN就好了,然后把验证页面放到自己的服务器上。
这里我提供我做的一个例子:
准备资源:
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 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"], redirect_uri=settings.WECHAT_CONFIG["redirect_uri"], state=request.session['user_info']['uid'] ) 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") # 用户UID 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") 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": settings.WECHAT_CONFIG['template_id'], "data": { "first": { "DATA": "你好~", "color": "#173177" }, "keyword1": { "DATA": "你好好好~~", "color": "#173177" }, } } ) result = res.json() return result result = send_custom_msg() print(result) if result.get('errcode') == 0: return HttpResponse('发送成功') return HttpResponse('发送失败')
setings.py
WECHAT_CONFIG = { 'app_id': 'wx8c38a44c7441a4d0', 'appsecret': '5441ab5ad5e5ee26128e79132105d6a6', 'redirect_uri': 'http://140.143.63.45:8080/callback/', 'template_id': "Pyt4EoBlGaItBSiJPr9dYHHOy1YSnD6HyRXUV82xsw0" }
urls.py
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/$', views.login), url(r'^bind/$', views.bind), url(r'^bind_qcode/$', views.bind_qcode), url(r'^callback/$', views.callback), url(r'^sendmsg/$', views.sendmsg), ]
然后填写配置信息Token (一定要与上面的views.php中的token一致)、URL
然后提交就可以了
如果提示失败,请检查Token与URL【如果是自己的域名和空间,请备案; 百度sae、新浪sae的需要自己申请而且认证通过(就是自己拍一个手握证件照上传,很简单的 最短2天就o了),这一步必须必】
第三步 :配置JS接口安全域名
这一步其实也很简单的,但是很多人在这一步浪费很长时间,
填这个域名是一定不要带protocol的,比如说 http://www.sagosoft.com/ 这样是不对的,这是URL不是域名
域名应该是类似 www.sagosoft.com这样的 【否则在微信js-sdk接入时会提示invalid url domain】
第四步 :手机微信扫描测试号二维码 关注测试公众号
第五步 :体验接口权限表-网页账号
域名填微信授权回调页面域名,如果是同一个域名跟上面的接口配置URL填一样即可
最后放一张另一个账号的完成图
1,让用户扫码关注我的公众号
2,引导用户让用户授权
--1,让用户给微信发请求 告诉微信授权
我们把请求地址生成一个二维码让用户扫
"https://open.weixin.qq.com/connect/oauth2/authorize?
appid={appid}&redirect_uri={redirect_uri}&response_type=code
&scope=snsapi_userinfo&state={state}#wechat_redirect"
--2,微信会给我们的redirect_uri发GET请求 code
没有给我们open_id, 需要做个二次认证
--3,再回调接口里 redirect_uri 向微信发请求
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": settings.WECHAT_CONFIG["app_id"],
"secret": settings.WECHAT_CONFIG["appsecret"],
"code": code,
"grant_type": 'authorization_code',
}
).json()
open_id = res.get("openid")
# 把用户的openid 存入数据库
3,发送消息
-- 给微信发送消息的接口发请求
"xxxxxxxxxxxxxxx?access_token"
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')
)
-- 获取access_token
相当于做了一个登陆认证
给微信获取token的接口发请求
带着我们的app_id 以及app_secret
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()