uniapp中微信小程序账号登录

<template>
	<view class="content">
        <!-- 登录适配 -->
             <!-- 最新版登录方法 -->
			<button 
           
            type='primary' lang="zh_CN" @tap="getUserProfile">新
            </button>
            <!-- 老版本登录方法 -->
			<button  type='primary' 
            open-type="getUserInfo" lang="zh_CN" @getuserinfo="bindGetUserInfo">老
            </button>
	</view>
</template>
<script>
	export default {
		data() {
			return {
                //用来判断用哪个登录
               appid:'去微信公众平台查看',
			   secret:'去微信公众平台->开发->开发设置获取生成',
			   code:''
            }
       },
       //监听页面加载
		onLoad() {
			uni.getSetting({
			   success(res) {
			      console.log(res.authSetting)
				  if(res.authSetting['scope.userInfo']){
					  console.log('登录了');
				  }else {
					  console.log('未登录');
				  }
			   }
			})
            //如果手机支持最新版登录就用新方法
			if (wx.getUserProfile) {
				this.canIUseGetUserProfile = true
			 }
			 
		},
        methods: {
            //老版登录接口(不再弹出登录弹框)
            bindGetUserInfo(e){
				console.log(e);
				if (e.detail.userInfo) {
					// console.log(e.detail.userInfo);
					uni.showLoading({
						title: '登录中'
					});
					//业务逻辑
					// console.log(res1);
					uni.login({
						success: res => {
							if (res.code) {
								//在此发起网络请求
								//请求后端给的登录接口,把res.code等相关参数带上
							} else {
								// console.log('登录失败!' + res.errMsg)
							}
						}
					})
				}
			},
            // 弹出登录弹框(新版)
			getUserProfile() {
			//推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息                                              均需用户确认
				// 开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
				uni.getUserProfile({
					desc: '用于获取您的个人信息', // s声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
					success: res1 => {
						console.log(res1);
						uni.showLoading({
							title: '登录中'
						});
						//业务逻辑
						// console.log(res1);
						 uni.login({
							success: res => {
								if (res) {
									console.log(res.code);
									this.code = res.code
									uni.request({
										url:`https://api.weixin.qq.com/sns/jscode2session?appid=${this.appid}&secret=${this.secret}&js_code=${this.code}&grant_type=authorization_code`,
									    success:(res)=>{
											console.log(res);
                                    //发起网络请求
                                    //请求后端给的登录接口,把res.code等相关参数带上
										}
									})
								} else {
									// console.log('登录失败!' + res.errMsg)
								}
							}
						}) 
					}
				})
			},
        }
   }
</script>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值