小程序如何获取code

  1. <button open-type="getUserInfo" hover-class='none' bindgetuserinfo="getUserInfoFun">.</button>
  1. wx.login({
  2. success: function (res) {
  3. var code = res.code;
  4. if (code) {
  5. console.log('获取用户登录凭证:' + code);
  6. // --------- 发送凭证 ------------------
  7. wx.request({
  8. url: 'https://www.my-domain.com/wx/onlogin',
  9. data: { code: code }
  10. })
  11. // ------------------------------------
  12. } else {
  13. console.log('获取用户登录态失败:' + res.errMsg);
  14. }
  15. }
  16. });

登录的时候需要拿到token值,需要跟后端配合才能拿到

小程序调用wx.login() 获取 临时登录凭证code ,并回传到开发者服务器

开发者服务器以code换取 用户唯一标识openid 和 会话密钥session_key

  1. // 登录
  2. wx.login({
  3. success: res => {
  4. // 发送 res.code 到后台换取 openId, sessionKey, unionId
  5. // console.log(res)
  6. if (res.code) {
  7. //发起网络请求
  8. wx.request({
  9. url: 'url',
  10. method: 'POST',
  11. data: {
  12. // x: '',
  13. // y: ''
  14. code: res.code //将code发给后台拿token
  15. },
  16. header: {
  17. 'content-type': 'application/json' // 默认值
  18. },
  19. success: function(res) {
  20. // 存token
  21. console.log('token=' + res.data.data.token)
  22. that.globalData.token = res.data.data.token; //拿到后将token存入全局变量 以便其他页面使用
  23. }
  24. })
  25. } else {
  26. console.log('获取用户登录态失败!' + res.errMsg)
  27. }
  28. }
  29. })
  1. // 检验、登录
  2. wx.checkSession({
  3. success: function() {
  4. //session_key 未过期,并且在本生命周期一直有效
  5. },
  6. fail: function() {
  7. //session_key 已经失效,需要重新执行登录流程
  8. wx.login({
  9. success: (res) => {
  10. if (res.code) {
  11. //发起网络请求
  12. wx.request({
  13. //开发者服务器通过code换取用户唯一标识openid 和 会话密钥session_key。
  14. url: 'https://test.com/onLogin',
  15. data: {
  16. // 临时登录凭证code,并回传到开发者服务器
  17. code: res.code
  18. },
  19. success: function(result) {
  20. //返回业务数据,前后端交互身份识别
  21. }
  22. })
  23. } else {
  24. console.log('登录失败!' + res.errMsg)
  25. }
  26. }
  27. });
  28. }
  29. })

授权获取用户信息

  1. // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope
  2. wx.getSetting({
  3. success(res) {
  4. if (!res.authSetting['scope.record']) {
  5. wx.authorize({
  6. scope: 'scope.record',
  7. success() {
  8. // 用户已经同意小程序使用录音功能,后续调用 wx.startRecord 接口不会弹窗询问
  9. wx.startRecord()
  10. }
  11. })
  12. }
  13. }
  14. })
  1. wx.authorize({scope: "scope.userInfo"}),无法弹出授权窗口,请使用
  2. <button open-type="getUserInfo"></button>
  1. wx.getSetting({
  2. success: (res)=>{
  3. if (res.authSetting['scope.userInfo']) {
  4. // 已经授权,可以直接调用 getUserInfo 获取头像昵称
  5. wx.getUserInfo({
  6. withCredentials: true,
  7. success: (res) => {
  8. console.log(res);
  9. }
  10. })
  11. }
  12. }
  13. });

授权和登录的意义

session_key 的作用

unionId 的作用,有哪些获取途径

在应用中如何保存用户登录态

新版api已废弃wx.authorize()

wx.getUserInfo(Object object)

调用前需要 用户授权 scope.userInfo。

注意:wx.authorize({scope: "scope.userInfo"}),无法弹出授权窗口,请使用

  1. <button open-type="getUserInfo"/>

一个用户相对于不同的微信应用会存在不同的openId

保存用户登录态

两种解决方案:前端保存和后端保存

  1. App({
  2. data:{
  3. titleList: [], //数据
  4. wxa_session: '', // 密钥
  5. openid: '',
  6. scene: ''
  7. },
  8. onLaunch: function () {
  9. try {
  10. // 同步清理本地数据缓存
  11. console.log('clear');
  12. wx.clearStorageSync()
  13. } catch (e) {
  14. // Do something when catch error
  15. }
  16. },
  17. // 定义登录函数
  18. userLogin:function(cb){
  19. var that = this
  20. wx.login({
  21. success: function (res) {
  22. if (res.code) {
  23. //发起网络请求
  24. wx.request({
  25. url: 'https://mp.weixin.qq.com/wxaintp/common?action=login&codetype=invoicediscern',
  26. data: {
  27. // 通过传递code获取openID 和 密钥
  28. code: res.code
  29. },
  30. success: function (res) {
  31. // console.log(res);
  32. if (res.data.base_resp.ret == 0){
  33. // 用户唯一标识openid 和 会话密钥session_key
  34. that.data.wxa_session = res.data.session_key;
  35. that.data.openid = res.data.openid;
  36. console.log(that.data.wxa_session);
  37. cb(); // 后续操作
  38. }
  39. else {
  40. // 参数有误
  41. wx.showToast({
  42. image: '/static/images/icon_fail@3x.png',
  43. title: res.data.base_resp.err_msg,
  44. })
  45. }
  46. }
  47. })
  48. } else {
  49. console.log('获取用户登录态失败!' + res.errMsg)
  50. }
  51. }
  52. });
  53. globalData:{
  54. userInfo:null
  55. },
  56. onShow: function(options) {
  57. console.log('app onShow');
  58. console.log(options);
  59. var that = this;
  60. if(options){
  61. that.data.scene = options.scene; //场景
  62. }
  63. }
  64. })
  1. App({
  2. // 获取token
  3. getToken: function() {
  4. var that = this;
  5. if (wx.getStorageSync("token") == null || wx.getStorageSync("token") == "") {
  6. console.log("请用户授权获取token");
  7. wx.redirectTo({
  8. url: '/pages/welcome/welcome',
  9. })
  10. } else {
  11. wx.switchTab({
  12. url: '/pages/index/index',
  13. })
  14. }
  15. },
  16. // 当小程序初始化完成时,会触发 onLaunch(全局只触发一次)
  17. onLaunch: function() {
  18. // 获取小程序更新机制兼容
  19. if (wx.canIUse('getUpdateManager')) {
  20. const updateManager = wx.getUpdateManager()
  21. updateManager.onCheckForUpdate(function(res) {
  22. // 请求完新版本信息的回调
  23. if (res.hasUpdate) {
  24. updateManager.onUpdateReady(function() {
  25. wx.showModal({
  26. title: '更新提示',
  27. content: '新版本已经准备好,是否重启应用?',
  28. success: function(res) {
  29. if (res.confirm) {
  30. // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
  31. updateManager.applyUpdate()
  32. }
  33. }
  34. })
  35. })
  36. updateManager.onUpdateFailed(function() {
  37. // 新的版本下载失败
  38. wx.showModal({
  39. title: '已经有新版本了哟~',
  40. content: '新版本已经上线啦~,请您删除当前小程序,重新搜索打开哟~',
  41. })
  42. })
  43. }
  44. })
  45. } else {
  46. // 如果希望用户在最新版本的客户端上体验您的小程序,可以这样子提示
  47. wx.showModal({
  48. title: '提示',
  49. content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
  50. })
  51. }
  52. var that = this;
  53. that.getToken();
  54. },
  55. // 当小程序启动,或从后台进入前台显示,会触发 onShow
  56. onShow: function(options) {
  57. },
  58. // 当小程序从前台进入后台,会触发 onHide
  59. onHide: function() {
  60. },
  61. // 当小程序发生脚本错误,或者 api 调用失败时,会触发 onError 并带上错误信息
  62. onError: function(msg) {
  63. },
  64. globalData: {
  65. "avatarUrl": null,
  66. "nickName": null,
  67. // userId: 用户编号
  68. "userId": null,
  69. // organId: 所属单位
  70. "organId": null,
  71. // idType:身份类型
  72. "idType": null,
  73. "uncheckedNUM": null,
  74. "attendNum": null,
  75. "beLateNum": null,
  76. "leaveNum": null,
  77. "token": null,
  78. "studentNo": null,
  79. }
  80. })
  1. // 获取全局变量
  2. const app = getApp();
  3. Page({
  4. // 页面的初始数据
  5. data: {
  6. progress_txt: '点击账号绑定...',
  7. },
  8. // 按钮
  9. drawProgressbg: function() {
  10. // 使用 wx.createContext 获取绘图上下文 context
  11. var ctx = wx.createCanvasContext('canvasProgressbg')
  12. ctx.setLineWidth(4); // 设置圆环的宽度
  13. ctx.setStrokeStyle('#20183b'); // 设置圆环的颜色
  14. ctx.setLineCap('round') // 设置圆环端点的形状
  15. ctx.beginPath(); //开始一个新的路径
  16. ctx.arc(110, 110, 100, 0, 2 * Math.PI, false);
  17. //设置一个原点(100,100),半径为90的圆的路径到当前路径
  18. ctx.stroke(); //对当前路径进行描边
  19. ctx.draw();
  20. },
  21. // 授权登录
  22. doAuthorization: function(e) {
  23. var that = this;
  24. console.log("调用了 doAuthorization 授权");
  25. // 授权 只为获取token
  26. wx.login({
  27. success: function(res) {
  28. console.log("login: code", res.code);
  29. // 发送至服务器
  30. wx.request({
  31. url: '',
  32. method: 'POST',
  33. header: {
  34. Authorization: "",
  35. 'Content-Type': 'application/x-www-form-urlencoded',
  36. },
  37. data: {
  38. mobile: 'wxecd372cca9b110e3@' + res.code,
  39. grant_type: 'mobile',
  40. },
  41. success: function(res) {
  42. // 进行判断
  43. console.log("button 成功", res.data);
  44. console.log("button token 成功", res.data.access_token);
  45. if (res.data.access_token == null || res.data.access_token == "") {
  46. wx.showModal({
  47. title: '提示',
  48. content: '请到公众号平台进行绑定账号',
  49. showCancel: false,
  50. success: function(res) {
  51. console.log("请绑定账号");
  52. }
  53. })
  54. } else {
  55. wx.setStorageSync("token", res.data.access_token);
  56. wx.showToast({
  57. title: '成功',
  58. icon: 'succes',
  59. duration: 1000,
  60. mask: true
  61. })
  62. setTimeout(function() {
  63. // 授权跳转 index
  64. wx.switchTab({
  65. url: '/pages/index/index',
  66. })
  67. wx.hideToast()
  68. }, 2000)
  69. }
  70. },
  71. // 失败
  72. fail: function(err) {
  73. console.log("token 失败", err);
  74. wx.showModal({
  75. title: '提示',
  76. content: '请到公众号平台进行绑定账号',
  77. showCancel: false,
  78. success: function(res) {      
  79. if (res.confirm) {        
  80. wx.navigateBack({          
  81. delta: 0        
  82. })      
  83. }    
  84. }
  85. })
  86. }
  87. })
  88. }
  89. })
  90. },
  91. // 生命周期函数--监听页面加载
  92. onLoad: function(options) {
  93. },
  94. // 生命周期函数--监听页面初次渲染完成
  95. onReady: function() {
  96. this.drawProgressbg();
  97. },
  98. // 生命周期函数--监听页面显示
  99. onShow: function() {
  100. },
  101. // 生命周期函数--监听页面隐藏
  102. onHide: function() {
  103. },
  104. // 生命周期函数--监听页面卸载
  105. onUnload: function() {
  106. }
  107. })

小程序如何获取code的更多相关文章

  1. 微信小程序如何获取openid

    微信小程序如何获取openid wx.login({ success: res => { // 发送 res.code 到后台换取 openId, sessionKey, unionId // ...

  2. 微信小程序验证码获取倒计时

    wxml <button disabled='{{disabled}}' bindtap="goGetCode">{{code}}</button> js ...

  3. 微信小程序后台获取用户的opeid

    1.微信小程序后台获取登录用户的openid,首先微信小程序将code传给后台服务器 wx.login({ success: function (res) { var code = res.code ...

  4. nodejs+koa+uniapp实现微信小程序登陆获取用户手机号及openId

    nodejs+koa+uniapp实现微信小程序登陆获取用户手机号及openId 前言: 我准备用nodejs+koa+uniapp实现一款餐饮点单小程序,以及nodejs+koa+vue实现后端管理 ...

  5. 【微信小程序】获取用户地理位置权限,二次请求授权,逆解析获取地址

    摘要:微信小程序内获取用户地理位置信息授权,被拒绝后二次获取,获取权限后逆解析得到用户所在省市区等.. 场景:商城类小程序,在首页时需展示附近门店,即用户刚进入小程序时就需要获取到用户位置信息 ste ...

  6. 微信小程序,获取二维码

    微信小程序,获取二维码 找到一篇很实用的博客,他已经写得很详细了,自己也懒得写,亲测有效 参考网址

  7. 【小程序】获取到的e.target与e.currentTarget区别

    [小程序]获取到的e.target与e.currentTarget区别:https://blog.csdn.net/qq_33744228/article/details/80310294 使用e.t ...

  8. 微信小程序 如何获取用户code

    1.首先需要获取code 使用 wx.login({ success: function(res) { console.log(res);//这里的返回值里面便包含code }, fail: func ...

  9. 微信小程序之获取验证码js

    在微信小程序中怎样实现获取验证码的倒计时功能捏,倒计时的原理是一样一样的,就是某些地方需要注意. 第一步:结构 <view class='get-code' wx:if="{{!isS ...

随机推荐

  1. hibernate session.createSQLQuery(sql); 通过命令删除

    @Override public boolean deleteBySql(String sql) { Session session = getSession(); @SuppressWarnings ...

  2. mongodb的配置文件详解()

    官方地址  https://docs.mongodb.com/manual/reference/configuration-options/#configuration-file 以下页面描述了Mon ...

  3. monkey命令解析

  4. HttpWebRequest 自定义header,Post发送请求,请求形式是json,坑爹的代码

    public static string PostMoths(string url, LoginDTO obj_model, Dictionary<string, string> dic ...

  5. python3 第三十二章 - 标准库概览

    1. 操作系统接口 os 模块提供很多函数与操作系统进行交互︰ >>> import os >>> os.getcwd() # 返回当前的工作目录 'C:\\Pyt ...

  6. Asp.net Zero 应用实战-官方示例PhoneBook学习1_修改1版

    适用Zero版本:ASP.NET Core & Angular 2+ (aspnet-zero-core-3.1.0). 该版本官方有两个solution文件夹:Angular(前端) 和 a ...

  7. Difference between Load / Stress / Performance Testing

    Load and stress testing are subsets of performance testing. Performance testing means how best somet ...

  8. 2019.03.26 bzoj4444: [Scoi2015]国旗计划(线段树+倍增)

    传送门 题意简述:现在给你一个长度为mmm的环,有nnn条互不包含的线段,问如果强制选第iii条线段至少需要用几条线段覆盖这个环,注意用来的覆盖的线段应该相交,即[1,3],[4,5][1,3],[4 ...

  9. Buffer.h

    #ifndef __NOXIMBUFFER_H__ #define __NOXIMBUFFER_H__ #include <cassert> #include <queue> ...

  10. <c:forEach>循环列表,获取勾选的checkbox中某个<td>的值

    <table> <!--列表表头 开始 --> <tr> <th><input type="checkbox" name=&q ...