Django后台通过微信小程序传过来的code获取用户唯一身份识别openid
一、微信小程序前端
- app.js
//app.js
App({
onLaunch: function () {
this.globalData = {
userInfo: null,
serverAddr: 'http://127.0.0.1:8000',
apiVersion: "/api/v1.0",
staticDir: "/static",
authType:4,
code: ""
}
// 登录
let that=this;
wx.login({
success(res) {
//js调用登陆命令获取到code
if (res.code) {
that.globalData.code = res.code
//通过code调用自己服务接口获取到openid
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
//获取用户信息
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
wx.getUserInfo({
success: res => {
this.globalData.userInfo = res.userInfo
if (this.userInfoReadyCallback){
this.userInfoReadyCallback(res)
}
}
})
}
}
})
},
onShow:function () {
}
})
// "iconPath": "",
// "selectedIconPath": ""
- index.js
//index.js
const WxParse = require('../../wxParse/wxParse.js');
const app = getApp();
var gloData = app.globalData
Page({
....
onLoad: function() {
// 获取用户信息
var that = this;
wx.getSetting({
success: res => {
//如果经过授权
if (res.authSetting['scope.userInfo']) {
this.setData({
hideBtn: true
})
//获取用户信息
wx.getUserInfo({
success: res => {
this.data.userInfo = res.userInfo
this.data.userInfo.code = gloData.code
wx.request({
url: gloData.serverAddr + gloData.apiVersion + "/auth/wxLogin/",
data: that.data.userInfo,
success: function (res) {
if(res.data.userType!=4)
{
gloData.authType = res.data.userType
that.setData({
hide: false,
authMSG:""
})
}else{
that.setData({
authMSG: "您未经杭州研一智控科技公司授权。请联系研一工作人员给您授权以正常使用本小程序!"
})
}
}
})
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
}
}
})
this.getNews("GET",0);
// let that = this;
// WxParse.wxParse('content', 'html', that.data.news[0].content, that, 5);
// console.log(that.data.news[0].content)
if (!wx.cloud) {
wx.redirectTo({
url: '../chooseLib/chooseLib',
})
return
}
}
)}
- app.js 中调用wx.login({})获取获取登录code
- index.js中请求授权,然后获取用户信息,并提交后台处理
二、后台获取openid
- appid、以及secret通过微信公众号获取,然后作者设置在了Django setting中
APPID = "wx秘密09"
SECRET = "6c秘密不给看7031d"
import requests
from django.conf import settings
class OpenidUtils(object):
url = "https://api.weixin.qq.com/sns/jscode2session"
appid = settings.APPID
secret = settings.SECRET
@classmethod
def get_openid(cls,code):
url = cls.url + "?appid=" + cls.appid + "&secret=" + cls.secret + "&js_code=" + code + "&grant_type=authorization_code"
return requests.get(url).json()
人生还有意义。那一定是还在找存在的理由