小程序如何获取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 ...
随机推荐
- unity导入TexturePacker处理
1.从Asset Store里下载TexturePackerImporter ,然后导入到项目中. 2.导入unity的一张大图和一个.tpsheet文件(注意原始图片也要在相同目录) 3.代码导入 ...
- Tigase-02 tigase-server7.1.0使用git 克隆下来,并在eclipse 上运行调试
继 Tigase-01 使用spark或spi登录Tigase服务器,这节说明下使用 eclipse git克隆 tigase-server7.1.0,并运行调试!最近有不少同学尝试去git clon ...
- Ubuntu 18.04 下如何配置mysql 及 配置远程连接
首先是大家都知道的老三套,啥也不说上来就放三个大招: sudo apt-get install mysql-server sudo apt isntall mysql-client sudo apt ...
- java将pdf文件转为word
import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.Output ...
- mysql第一课,数据库的简单简单操作方法(配图略虐狗)
mysql -u root -p 并输入密码进入mysql管理界面 show databases; 显示数据库列表 use 数据库名; 进入该数据库 show tables;显示表列表 建立新表 添加 ...
- 结果集ResultSet
我们访问数据库时候经常见到这样遍历结果集 conn = DBHelper.getConnection(); String sql = "select * from items"; ...
- 2019.03.26 bzoj4448: [Scoi2015]情报传递(归并排序+树链剖分)
传送门 题意简述: 给一棵nnn个点的树,树上每个点表示一个情报员,一共有mmm天,每天会派发以下两种任务中的一个任务: 1.搜集情报:指派T号情报员搜集情报 2.传递情报:将一条情报从X号情报员传递 ...
- shiro简单配置 (写的不错 收藏一下)
抄袭的连接:https://blog.csdn.net/clj198606061111/article/details/24185023 注:这里只介绍spring配置模式. 因为官方例子虽然中有更加 ...
- Goldwave-5.7[逆向流程+算法分析]
目标程序:Goldwave 5.7 分析工具: 1.OllyDbg 2.IDAPro 目的:用C语言写Goldwave-5.7的注册机. 0x0思路: 1.注册机准备: 功能:输入用户名后经过计算输出 ...
- k8s1.13.3安装istio(helm方式)
官方文档:https://istio.io/zh/docs/setup/kubernetes/install/helm/ 一.环境信息 centos7 k8s1.13.3 主机名 ip cpu ram ...