• 微信小程序开发笔记1——登录实现


    微信小程序登录实现

    说明:

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

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

    3.之后,开发者服务器可以根据用户标识来生成自定义登录态,用于后续业务逻辑中前后端交互时识别用户身份。

    举例:app.js文件

    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;  //场景
    	    }    
      }	 
    })
    

    —— 至此完毕,更多精彩请看下一笔记。

  • 相关阅读:
    getRandomInt getRandomString
    git 换行符替换
    Versions maven plugin 修改版本
    spotless-maven-plugin java代码自动格式化mvn spotless:apply -fn
    eclipse.ini
    JVM架构和GC垃圾回收机制
    查看搜狗浏览器记住的密码
    TestGc finalize()
    Storm个人学习总结
    mongo嵌套查询
  • 原文地址:https://www.cnblogs.com/Wisdon/p/8721383.html
Copyright © 2020-2023  润新知