微信小程序登录最佳实践

app.js

1 检查本地是不是有openid,如果没后那么去获取

2 为什么需要openid ?因为在后续对微信的接口的调用会用到,比如支付,比如地图之类的。

const config = require("./utils/config.js")
App({
  onLaunch: function () {
    let that = this;
    that.checkOpenId()
  },
  


// 检查本地是不是有登录标识
  checkOpenId:function(){
      var openId = wx.getStorageSync("openId");
      if(!openId){
        this.getOpenId();                
      }
  }, 


  getOpenId:function(){ 
    var that = this;
    wx.login({
      success(res) {
        if(res.code){
          // 发送请求获取openId
          wx.request({ 
            url:config.loginUrl,
            data:{  
              code:res.code,  // 临时登录凭证
            },
            success(res){  
              console.log(res.data.openid);
              wx.setStorageSync("openid",JSON.stringify(res.data.openid));
            },
            fail(){
              wx.showToast({
                title: '链接失败',
              })
            }
          })
        }
      },
      fail(res){
          console.log("登录失败");
      }
    })
  },   

 



    
})


 

 

 

首页,里面

1 本地获取userinfo(用户信息),如果不存在,那么显示一个登录面板,点击之后调用微信api 获取用户,

2 把用户信息存储在本地

3 把用户信息发送到自己的服务器存储。

 

Page({
   //页面的初始数据
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    userInfo:false
  },

  checkUserInfo(){
    // 检查本地是不是有flag 如果没有那么显示登录面板
    if (wx.getStorageSync("userInfo")){
      this.setData({
         userInfo:true,
      })
    }
  },
  getUserInfo(e) {
    console.log(e.detail);
    // 发送request,发送给服务器,成功了,那么本地存储一个标志  
    // userinfo = true 
     wx.setStorageSync("userInfo",JSON.stringify(e.detail.userInfo))
     this.setData({
        userInfo:true
     })
  }, 

  goDetail(e){
    var data = e.currentTarget.dataset;
    wx.navigateTo({
      url: '../detail/detail?name='+data.name+'&age='+data.age,
    })
  },




  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.checkUserInfo()
  },

 

登录面板


<view class="userInfo" wx:if="{{!userInfo}}">
        <button wx:if="{{canIUse}}" open-type="getUserInfo" 
                bindgetuserinfo="getUserInfo">授权登录</button>
        <view wx:else>请升级微信版本</view> 
        <button>
        <navigator open-type="exit" target="miniProgram">取消并退出</navigator>
        </button>
</view>

后台 java

用 code ,appid 和appsecrt 从腾讯的接口获取 openid 和 sessiojkey


    public static String AppSecret = "747e4550714d43499ebe4200da781b91";
    public static String appid = "wx1f045119090a0dc0";


    @GetMapping("/getOpenId")
    public String getOpenId(String code) throws IOException {
        System.out.println(code);
         return HttpGet(code);

    }







    /**
     * GET---无参测试
     *
     * @date 2018年7月13日 下午4:18:50
     */

    public String HttpGet(String code) {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Get请求
        HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+AppSecret+"&js_code="+code+"&grant_type=authorization_code");
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                String responseData = EntityUtils.toString(responseEntity);
//                responseEntity 是数据流,不可以直接对数据流操作两次,数据流是一次性的。
                System.out.println("响应内容为:" + responseData);
                return responseData;
            }else{
                return null;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                // 释放资源
                httpClient.close();
                response.close();

            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值