uniapp第三方登录
开发跨平台app, 难免会涉及第三方账号授权登录
以下代码中,微信、qq、微博三大平台返回的字段不同, 需要自行处理
该代码会用到provider,参考《获取服务提供商》篇
<template>
<view class="auth">
<!-- #ifdef APP-PLUS -->
<image src="../../static/wechat.png" data-loginType="weixin" @click="login"></image>
<image src="../../static/qq.png" data-loginType="qq" @click="login"></image>
<image src="../../static/weibo.png" data-loginType="sinaweibo" @click="login"></image>
<!-- #endif -->
<!-- #ifdef MP-WEIXIN -->
<button type="default" open-type="getUserInfo" @getuserinfo="xcxLogin" withCredentials="true">小程序登录</button>
<!-- #endif -->
</view>
</template>
<script>
export default {
data(){
    return {};
},
onLoad() {   
},
methods: {
    login(e){
        let loginType = e.currentTarget.dataset.logintype;
        uni.login({
          provider: loginType,
          success: function (loginRes) {//console.log(loginRes.authResult);            
              uni.getUserInfo({
                  provider: loginType,
                  success: function (infoRes) {
                      //console.log(JSON.stringify(infoRes))
                      var openId = '';    //如果开放平台申请了应用互通,可获取unionId
                      var nickName = '';
                      if (loginType == 'weixin') {
                          openId = infoRes.userInfo.openId;
                          nickName = infoRes.userInfo.nickName;
                      } else if (loginType == 'qq') {
                          openId = infoRes.userInfo.openId;
                          nickName = infoRes.userInfo.nickname;
                      } else if (loginType == 'sinaweibo') {
                          openId = infoRes.userInfo.id;
                          nickName = infoRes.userInfo.nickname;
                      }
                  },
              });            
          }
        });
    },
    xcxLogin(res){
        uni.login({
            provider: 'weixin',
            success: function(loginRes) {
                //console.log(loginRes);
                let code = loginRes.code;                
                uni.getUserInfo({
                    provider: 'weixin',
                    success: function(infoRes) {
                        console.log('昵称:' + infoRes.userInfo.nickName + ', 头像:' + infoRes.userInfo.avatarUrl);
                    }
                });                
                // 将用户登录code传递到后台置换用户SessionKey、OpenId等信息
                // 服务端可让客户端把code、昵称、头像等信息一并传入,服务端将code换取为openId后保存,并返回access_token
                uni.request({
                    url: '服务器地址',
                    data: {
                        code: code,
                    },
                    method: 'GET',
                    header: {
                        'content-type': 'application/json'
                    },
                    success: (res) => {    //openId、或SessionKdy存储//隐藏loading
                        uni.hideLoading();
                    }
                });
                
                
            }
        });
    }
}
}
</script>