小程序如何获取code
小程序如何获取code
<button open-type="getUserInfo" hover-class='none' bindgetuserinfo="getUserInfoFun">.</button>
wx.login({
success: function (res) {
var code = res.code;
if (code) {
console.log('获取用户登录凭证:' + code);
// --------- 发送凭证 ------------------
wx.request({
url: 'https://www.my-domain.com/wx/onlogin',
data: { code: code }
})
// ------------------------------------
} else {
console.log('获取用户登录态失败:' + res.errMsg);
}
}
});
登录的时候需要拿到token值,需要跟后端配合才能拿到
小程序调用wx.login() 获取 临时登录凭证code ,并回传到开发者服务器
开发者服务器以code换取 用户唯一标识openid 和 会话密钥session_key
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
// console.log(res)
if (res.code) {
//发起网络请求
wx.request({
url: 'url',
method: 'POST',
data: {
// x: '',
// y: ''
code: res.code //将code发给后台拿token
},
header: {
'content-type': 'application/json' // 默认值
},
success: function(res) {
// 存token
console.log('token=' + res.data.data.token)
that.globalData.token = res.data.data.token; //拿到后将token存入全局变量 以便其他页面使用
}
})
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
}
})
// 检验、登录
wx.checkSession({
success: function() {
//session_key 未过期,并且在本生命周期一直有效
},
fail: function() {
//session_key 已经失效,需要重新执行登录流程
wx.login({
success: (res) => {
if (res.code) {
//发起网络请求
wx.request({
//开发者服务器通过code换取用户唯一标识openid 和 会话密钥session_key。
url: 'https://test.com/onLogin',
data: {
// 临时登录凭证code,并回传到开发者服务器
code: res.code
},
success: function(result) {
//返回业务数据,前后端交互身份识别
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
});
}
})
授权获取用户信息
// 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope
wx.getSetting({
success(res) {
if (!res.authSetting['scope.record']) {
wx.authorize({
scope: 'scope.record',
success() {
// 用户已经同意小程序使用录音功能,后续调用 wx.startRecord 接口不会弹窗询问
wx.startRecord()
}
})
}
}
})
wx.authorize({scope: "scope.userInfo"}),无法弹出授权窗口,请使用
<button open-type="getUserInfo"></button>
wx.getSetting({
success: (res)=>{
if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称
wx.getUserInfo({
withCredentials: true,
success: (res) => {
console.log(res);
}
})
}
}
});
授权和登录的意义
session_key 的作用
unionId 的作用,有哪些获取途径
在应用中如何保存用户登录态
新版api已废弃wx.authorize()
wx.getUserInfo(Object object)
调用前需要 用户授权 scope.userInfo。
注意:wx.authorize({scope: "scope.userInfo"}),无法弹出授权窗口,请使用
<button open-type="getUserInfo"/>
一个用户相对于不同的微信应用会存在不同的openId
保存用户登录态
两种解决方案:前端保存和后端保存
App({
data:{
titleList: [], //数据
wxa_session: '', // 密钥
openid: '',
scene: ''
},
onLaunch: function () {
try {
// 同步清理本地数据缓存
console.log('clear');
wx.clearStorageSync()
} catch (e) {
// Do something when catch error
}
},
// 定义登录函数
userLogin:function(cb){
var that = this
wx.login({
success: function (res) {
if (res.code) {
//发起网络请求
wx.request({
url: 'https://mp.weixin.qq.com/wxaintp/common?action=login&codetype=invoicediscern',
data: {
// 通过传递code获取openID 和 密钥
code: res.code
},
success: function (res) {
// console.log(res);
if (res.data.base_resp.ret == 0){
// 用户唯一标识openid 和 会话密钥session_key
that.data.wxa_session = res.data.session_key;
that.data.openid = res.data.openid;
console.log(that.data.wxa_session);
cb(); // 后续操作
}
else {
// 参数有误
wx.showToast({
image: '/static/images/icon_fail@3x.png',
title: res.data.base_resp.err_msg,
})
}
}
})
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
}
});
globalData:{
userInfo:null
},
onShow: function(options) {
console.log('app onShow');
console.log(options);
var that = this;
if(options){
that.data.scene = options.scene; //场景
}
}
})
App({
// 获取token
getToken: function() {
var that = this;
if (wx.getStorageSync("token") == null || wx.getStorageSync("token") == "") {
console.log("请用户授权获取token");
wx.redirectTo({
url: '/pages/welcome/welcome',
})
} else {
wx.switchTab({
url: '/pages/index/index',
})
}
},
// 当小程序初始化完成时,会触发 onLaunch(全局只触发一次)
onLaunch: function() {
// 获取小程序更新机制兼容
if (wx.canIUse('getUpdateManager')) {
const updateManager = wx.getUpdateManager()
updateManager.onCheckForUpdate(function(res) {
// 请求完新版本信息的回调
if (res.hasUpdate) {
updateManager.onUpdateReady(function() {
wx.showModal({
title: '更新提示',
content: '新版本已经准备好,是否重启应用?',
success: function(res) {
if (res.confirm) {
// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
updateManager.applyUpdate()
}
}
})
})
updateManager.onUpdateFailed(function() {
// 新的版本下载失败
wx.showModal({
title: '已经有新版本了哟~',
content: '新版本已经上线啦~,请您删除当前小程序,重新搜索打开哟~',
})
})
}
})
} else {
// 如果希望用户在最新版本的客户端上体验您的小程序,可以这样子提示
wx.showModal({
title: '提示',
content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
})
}
var that = this;
that.getToken();
},
// 当小程序启动,或从后台进入前台显示,会触发 onShow
onShow: function(options) {
},
// 当小程序从前台进入后台,会触发 onHide
onHide: function() {
},
// 当小程序发生脚本错误,或者 api 调用失败时,会触发 onError 并带上错误信息
onError: function(msg) {
},
globalData: {
"avatarUrl": null,
"nickName": null,
// userId: 用户编号
"userId": null,
// organId: 所属单位
"organId": null,
// idType:身份类型
"idType": null,
"uncheckedNUM": null,
"attendNum": null,
"beLateNum": null,
"leaveNum": null,
"token": null,
"studentNo": null,
}
})
// 获取全局变量
const app = getApp();
Page({
// 页面的初始数据
data: {
progress_txt: '点击账号绑定...',
},
// 按钮
drawProgressbg: function() {
// 使用 wx.createContext 获取绘图上下文 context
var ctx = wx.createCanvasContext('canvasProgressbg')
ctx.setLineWidth(4); // 设置圆环的宽度
ctx.setStrokeStyle('#20183b'); // 设置圆环的颜色
ctx.setLineCap('round') // 设置圆环端点的形状
ctx.beginPath(); //开始一个新的路径
ctx.arc(110, 110, 100, 0, 2 * Math.PI, false);
//设置一个原点(100,100),半径为90的圆的路径到当前路径
ctx.stroke(); //对当前路径进行描边
ctx.draw();
},
// 授权登录
doAuthorization: function(e) {
var that = this;
console.log("调用了 doAuthorization 授权");
// 授权 只为获取token
wx.login({
success: function(res) {
console.log("login: code", res.code);
// 发送至服务器
wx.request({
url: '',
method: 'POST',
header: {
Authorization: "",
'Content-Type': 'application/x-www-form-urlencoded',
},
data: {
mobile: 'wxecd372cca9b110e3@' + res.code,
grant_type: 'mobile',
},
success: function(res) {
// 进行判断
console.log("button 成功", res.data);
console.log("button token 成功", res.data.access_token);
if (res.data.access_token == null || res.data.access_token == "") {
wx.showModal({
title: '提示',
content: '请到公众号平台进行绑定账号',
showCancel: false,
success: function(res) {
console.log("请绑定账号");
}
})
} else {
wx.setStorageSync("token", res.data.access_token);
wx.showToast({
title: '成功',
icon: 'succes',
duration: 1000,
mask: true
})
setTimeout(function() {
// 授权跳转 index
wx.switchTab({
url: '/pages/index/index',
})
wx.hideToast()
}, 2000)
}
},
// 失败
fail: function(err) {
console.log("token 失败", err);
wx.showModal({
title: '提示',
content: '请到公众号平台进行绑定账号',
showCancel: false,
success: function(res) {
if (res.confirm) {
wx.navigateBack({
delta: 0
})
}
}
})
}
})
}
})
},
// 生命周期函数--监听页面加载
onLoad: function(options) {
},
// 生命周期函数--监听页面初次渲染完成
onReady: function() {
this.drawProgressbg();
},
// 生命周期函数--监听页面显示
onShow: function() {
},
// 生命周期函数--监听页面隐藏
onHide: function() {
},
// 生命周期函数--监听页面卸载
onUnload: function() {
}
})
小程序如何获取code的更多相关文章
- 微信小程序如何获取openid
微信小程序如何获取openid wx.login({ success: res => { // 发送 res.code 到后台换取 openId, sessionKey, unionId // ...
- 微信小程序验证码获取倒计时
wxml <button disabled='{{disabled}}' bindtap="goGetCode">{{code}}</button> js ...
- 微信小程序后台获取用户的opeid
1.微信小程序后台获取登录用户的openid,首先微信小程序将code传给后台服务器 wx.login({ success: function (res) { var code = res.code ...
- nodejs+koa+uniapp实现微信小程序登陆获取用户手机号及openId
nodejs+koa+uniapp实现微信小程序登陆获取用户手机号及openId 前言: 我准备用nodejs+koa+uniapp实现一款餐饮点单小程序,以及nodejs+koa+vue实现后端管理 ...
- 【微信小程序】获取用户地理位置权限,二次请求授权,逆解析获取地址
摘要:微信小程序内获取用户地理位置信息授权,被拒绝后二次获取,获取权限后逆解析得到用户所在省市区等.. 场景:商城类小程序,在首页时需展示附近门店,即用户刚进入小程序时就需要获取到用户位置信息 ste ...
- 微信小程序,获取二维码
微信小程序,获取二维码 找到一篇很实用的博客,他已经写得很详细了,自己也懒得写,亲测有效 参考网址
- 【小程序】获取到的e.target与e.currentTarget区别
[小程序]获取到的e.target与e.currentTarget区别:https://blog.csdn.net/qq_33744228/article/details/80310294 使用e.t ...
- 微信小程序 如何获取用户code
1.首先需要获取code 使用 wx.login({ success: function(res) { console.log(res);//这里的返回值里面便包含code }, fail: func ...
- 微信小程序之获取验证码js
在微信小程序中怎样实现获取验证码的倒计时功能捏,倒计时的原理是一样一样的,就是某些地方需要注意. 第一步:结构 <view class='get-code' wx:if="{{!isS ...
随机推荐
- hibernate session.createSQLQuery(sql); 通过命令删除
@Override public boolean deleteBySql(String sql) { Session session = getSession(); @SuppressWarnings ...
- mongodb的配置文件详解()
官方地址 https://docs.mongodb.com/manual/reference/configuration-options/#configuration-file 以下页面描述了Mon ...
- monkey命令解析
- HttpWebRequest 自定义header,Post发送请求,请求形式是json,坑爹的代码
public static string PostMoths(string url, LoginDTO obj_model, Dictionary<string, string> dic ...
- python3 第三十二章 - 标准库概览
1. 操作系统接口 os 模块提供很多函数与操作系统进行交互︰ >>> import os >>> os.getcwd() # 返回当前的工作目录 'C:\\Pyt ...
- Asp.net Zero 应用实战-官方示例PhoneBook学习1_修改1版
适用Zero版本:ASP.NET Core & Angular 2+ (aspnet-zero-core-3.1.0). 该版本官方有两个solution文件夹:Angular(前端) 和 a ...
- Difference between Load / Stress / Performance Testing
Load and stress testing are subsets of performance testing. Performance testing means how best somet ...
- 2019.03.26 bzoj4444: [Scoi2015]国旗计划(线段树+倍增)
传送门 题意简述:现在给你一个长度为mmm的环,有nnn条互不包含的线段,问如果强制选第iii条线段至少需要用几条线段覆盖这个环,注意用来的覆盖的线段应该相交,即[1,3],[4,5][1,3],[4 ...
- Buffer.h
#ifndef __NOXIMBUFFER_H__ #define __NOXIMBUFFER_H__ #include <cassert> #include <queue> ...
- <c:forEach>循环列表,获取勾选的checkbox中某个<td>的值
<table> <!--列表表头 开始 --> <tr> <th><input type="checkbox" name=&q ...