我们也知道微信小程序前段时间更新了获取用户信息方法(区别),今天介绍一下,最新版uniapp获取用户信息(支付宝和微信小程序)
直接上代码:

	<view class='bottom flex'>
	    <!-- #ifdef MP-WEIXIN -->				
		<button  type="primary"  @tap="getUserInfo">去授权</button>
		<!-- #endif -->
		<!-- #ifdef MP-ALIPAY -->
		<button scope="userInfo" open-type="getAuthorize" @getAuthorize="onGetAuthorize">去授权zfb</button>		
		<!-- #endif -->
	</view>

<script>
export default{
data(){
	return {
		userInfo:{},
	}
},
mounted()  {

},
methods:{
	 //#ifdef MP-ALIPAY
	 onGetAuthorize(){	
		this.getUserInfo();
	 },
     //#endif
	 getUserInfo:(){
		let  that = this , code = this.getCode();
		return new Promise( (resolve,reject) => {
			//#ifdef MP-WEIXIN
			if(wx.canIUse('getUserProfile')){
				uni.getUserProfile({
					lang: 'zh_CN',
					desc:'获取登录信息',
					success(user) {
						if(code) user.code = code;
						that.userInfo=user
					},
					fail(res){
						reject(res);
					}
				})	
			}else{
				uni.getUserInfo({
					lang: 'zh_CN',
					success(user) {					
						if(code) user.code = code;
						that.userInfo=user
					},
					fail(res){
						reject(res);
					}
				})
			}
			//#endif
			//#ifdef MP-ALIPAY
			uni.getUserInfo({
				lang: 'zh_CN',
				success(user) {
					if(code) user.code = code;
                    that.userInfo=user
				},
				fail(res){
					reject(res);
				}
			})
			//#endif
		})
	
    },

    async getCode(){
		let provider = await this.getProvider();
		return new Promise((resolve,reject)=>{
			uni.login({
				provider:provider, //服务供应商
				success(res) {
					return resolve(res.code);
				},
				fail(e){
					return reject(null);
				}
			})
		})
	}

	getProvider()
	{
		return new Promise((resolve,reject)=>{
			uni.getProvider({
				service:'oauth',
				success(res) {
					resolve(res.provider);
				},
				fail() {
					resolve(false);
				}
			});
		});
	}	
			
}			
}
</script>

注意:uni.getUserInfo和uni.getUserProfile都必须是用户手动点击才能触发

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐