uni-app微信小程序登录授权的实现

编程学习 2021-07-04 15:03www.dzhlxh.cn编程入门
这篇文章主要介绍了uni-app微信小程序登录授权的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们狼蚁网站SEO优化随着长沙网络推广来一起学习学习吧

微信小程序授权是非常简单和常用的功能,但为了方便,还是在此记录一下要点:

首先是需要用到一个授权按钮来触发获取用户信息授权: 关键在于 open-type 为 getUserInfo , 然后有个@getuserinfo的事件,把获取授权接口写到该事件里面去

<button class="sys_btn" open-type="getUserInfo" lang="zh_CN" @getuserinfo="appLoginWx">{{loginInfo.openid != "" && loginInfo.openid != undefined ? "已授权" : "小程序授权"}}</button>

方法如下:

appLoginWx(){
        // #ifdef MP-WEIXIN
          uni.getProvider({
           service: 'oauth',
           success: function (res) {
            if (~res.provider.indexOf('weixin')) {
              uni.login({
                provider: 'weixin',
                success: (res) => {
                  _self.authorization = res.code;
                  uni.getUserInfo({
                    provider: 'weixin',
                    success: (info) => {//这里请求接口
                      console.log(res);
                      console.log(info);
                      
                    },
                    fail: () => {
                      uni.showToast({title:"微信登录授权失败",icon:"none"});
                    }
                  })
              
                },
                fail: () => {
                  uni.showToast({title:"微信登录授权失败",icon:"none"});
                }
              })
              
            }else{
              uni.showToast({
                title: '请先安装微信或升级版本',
                icon:"none"
              });
            }
           }
          });
          //#endif
      }

在 uni.login 和 uni.getUserInfo 被调用后,你可以获取到以下值用于继续请求后端给你的接口:

常用的值大概有:code 、iv 、encryptedData 和 个人基本信息,这些可以传给后端交换得到openid。

如果需要知道用户当前是否已经授权,则可以使用如下代码:

uniapp的授权文档,可以判断不同的授权类型:

// #ifdef MP-WEIXIN
      uni.getSetting({
       success(res) {
        console.log("授权:",res);
        if (!res.authSetting['scope.userInfo']) {
          //这里调用授权
          console.log("当前未授权");
        } else {
          //用户已经授权过了
          console.log("当前已授权");
        }
       }
      })
      //#endif

到此这篇关于uni-app微信小程序登录授权的实现的文章就介绍到这了,更多相关uni-app小程序登录授权内容请搜索狼蚁SEO以前的文章或继续浏览狼蚁网站SEO优化的相关文章希望大家以后多多支持狼蚁SEO!

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板