后端写的小程序授权登录代码测试,两步走。

index.js

Page({
  data: {
   //判断小程序的API,回调,参数,组件等是否在当前版本可用。
   canIUse: wx.canIUse('button.open-type.getUserInfo'),
   isHide: true,
   token:''
  },
  
  onLoad: function() {
   var that = this;
   // 查看是否授权
   wx.getSetting({
    success: function(res) {
      console.log(res)
     if (res.authSetting['scope.userInfo']) {
      wx.login({
        success: res => {
          // 获取到用户的 code 之后:res.code
          console.log("用户的code:" + res.code);
          // 可以传给后台,再经过解析获取用户的 openid
          // 或者可以直接使用微信的提供的接口直接获取 openid ,方法如下:
          wx.request({
          // 自行补上自己的 APPID 和 SECRET
          url: 'http://127.0.0.1:8888/api/auth?code=' + res.code + '&grant_type=authorization_code',
          success: res => {
            // 获取到用户的 openid
            console.log( res.data);
            that.token = res.data.data.token;
          }
          });
        }
      });
     } else {
      // 用户没有授权
      // 改变 isHide 的值,显示授权页面
      that.setData({
       isHide: true
      });
     }
    }
   });
  },
  
  bindGetUserInfo: function() {
    var that =this;
    wx.showModal({
      title: '温馨提示',
      content: '正在请求您的个人信息',
      success(res) {
        if (res.confirm) {
          wx.getUserProfile({
          desc: "获取你的昵称、头像、地区及性别",
          success: res => {
            console.log(res)
              wx.request({
              // 自行补上自己的 APPID 和 SECRET
              url: 'http://127.0.0.1:8888/api/auth/login',
              data: {
                  encryptedData: res.encryptedData,
                  iv: res.iv,
              },
              method:'post',
              header:{
              "Content-Type":"appliaction/json",
              "Authorization":"Bearer " + that.token
              },
              success: res => {
              // 获取到用户的 openid
              console.log( res.data);
              that.setData({
                isHide: false
               });
              }
           });
          },
          fail: res => {
             //拒绝授权
             console.log(res)
            that.showErrorModal('您拒绝了请求');
            return;
          }
        })} else if (res.cancel) {
          //拒绝授权 showErrorModal是自定义的提示
          that.showErrorModal('您拒绝了请求');
          return;
        }
      }
    })
  }
 })

index.wxml


 
  
   
  
 
  
   申请获取以下权限
   获得你的公开信息(昵称,头像等)
  
 
  
 
 请升级微信版本

 

 Hello world

index.wxss

.header {
  margin: 90rpx 0 90rpx 50rpx;
  border-bottom: 1px solid #ccc;
  text-align: center;
  width: 650rpx;
  height: 300rpx;
  line-height: 450rpx;
 }
  
 .header image {
  width: 200rpx;
  height: 200rpx;
 }
  
 .content {
  margin-left: 50rpx;
  margin-bottom: 90rpx;
 }
  
 .content text {
  display: block;
  color: #9d9d9d;
  margin-top: 40rpx;
 }
  
 .bottom {
  border-radius: 80rpx;
  margin: 70rpx 50rpx;
  font-size: 35rpx;
 }

你可能感兴趣的:(后端写的小程序授权登录代码测试,两步走。)