微信一键登录代码片段

<template>
	<view style="position:relative;">
		<!-- <img style="width: 100%; height: 1120rpx;" src="/pagesA/static/background/background.png" /> -->
		<image style="padding-left:170rpx;padding-top:180rpx;width:580rpx;height:560rpx;" src="/static/logo.png">
			<view style="position: fixed;
		top: 0;
		left: 0;
		right: 0%;
		bottom: 0;
		background-color: #21D4FD;
		background-image: linear-gradient(19deg, #21D4FD 0%, #B721FF 100%);
		z-index: -1;"></view>
			<button style="position:absolute; width:456rpx;left:77px; top:340px; border-radius: 20px;" lang="zh_CN"
				@click="getPhoneNumber">微信用户快捷登录</button>
			<span style="position:absolute; width:456rpx;left:57px; top:390px;color: white;"
				@click="handleLogin">用户名密码登录</span>
	</view>
</template>

<script>
	import {
		wexinLogin
	} from "@/api/login";

	export default {
		data() {
			return {
				tableNo: '',
			}
		},
		onLoad: function(e) {
			//如何解析
			const url = decodeURIComponent(e.q); //这里的值就是二维码里带的参数值   
			console.log("二维码链接:" + url);
			e = this.GetWxMiniProgramUrlParam(url); //此处就是我们要获取的参数 json
			this.tableNo = e.tableNo
			console.log("设备号:" + this.tableNo);
		},
		methods: {
			GetWxMiniProgramUrlParam(url) {
				let theRequest = {};
				if (url.indexOf("#") != -1) {
					const str = url.split("#")[1];
					const strs = str.split("&");
					for (let i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
					}
				} else if (url.indexOf("?") != -1) {
					const str = url.split("?")[1];
					const strs = str.split("&");
					for (let i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
					}
				}
				return theRequest;
			},
			getPhoneNumber() {
				var that = this;
				uni.showLoading({ // 展示加载框
					title: '加载中',
				});
				uni.getUserInfo({
					provider: 'weixin',
					success: function(info) {
						// 获取用户信息成功, info.authResult保存用户信息
						console.log("用户信息:" + info.userInfo)
						that.nickName = info.userInfo.nickName //用户名
						that.avatarUrl = info.userInfo.avatarUrl //用户头像
						//that.iv = e.detail.iv //用户解密手机的参数
						//that.encryptedData = e.detail.encryptedData //用户解密手机的参数
						uni.login({
							"provider": "weixin",
							"onlyAuthorize": true, // 微信登录仅请求授权认证
							success: function(event) {
								const {
									code
								} = event
								console.log("code" + event.code)
								var params = {
									tableNo: that.tableNo,
									wxCode: event.code,
									//encryptedData: that.encryptedData,
									//iv: that.iv,
									userInfo: info.userInfo
								}
								//微信登录
								wexinLogin(params).then(res => {
									if (res.code == 200) {
										uni.showToast({
											title: '登录成功',
											icon: 'success',
											mask: true,
										});
										//清除原有数据
										uni.removeStorageSync('userInfo');
										uni.removeStorageSync('token');
										uni.removeStorageSync();
										//存储用户信息
										uni.setStorageSync('App-Token', res.data.token)
										uni.setStorageSync('data', res.data)
										console.log('用户数据', res.data)
										uni.switchTab({
											url: "/pages/index"
										})
									}
								})
							},
							fail: function(err) {
								// 登录授权失败  
								//err.code是错误码
							}
						})
					}
				})
			},
			handleLogin() {
				// 跳转页面
				uni.navigateTo({
					url: '/pages/login'
				})
			}
		}
	}
</script>
<style>
	page {
		background-color: #ffffff;
	}

	.header {
		margin: 90rpx 0 90rpx 50rpx;
		border-bottom: 1px solid #ccc;
		text-align: center;
		width: 650rpx;
		height: 300rpx;
		line-height: 450rpx;
	}

	.header image {
		width: 200rpx;
		height: 200rpx;
	}

	.content {
		margin-left: 50rpx;
		margin-bottom: 90rpx;
	}

	.content text {
		display: block;
		color: #9d9d9d;
		margin-top: 40rpx;
	}

	.bottom {
		border-radius: 80rpx;
		margin: 70rpx 50rpx;
		font-size: 35rpx;
	}

	<style>

/**
     * 获取微信授权
     * @param wxCode
     * @return
     */
    private Map<String, String> wxAuth(String wxCode) {
        HashMap<String, String> hashMap = new HashMap<>();
        if (wxCode == null) {
            return null;
        }
        String sessionKey = null;
        String openId = null;
        try {
            WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(wxCode);
            sessionKey = result.getSessionKey();
            openId = result.getOpenid();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
        if (sessionKey == null || openId == null) {
            return null;
        }
        hashMap.put("openId", openId);
        hashMap.put("sessionKey", sessionKey);
        return hashMap;
    }

    /**
     * 微信登录
     *
     * @param wxLoginInfo 请求内容,{ code: xxx, userInfo: xxx }
     * @return 登录结果
     */
    @PostMapping("/loginByWeixin")
    public AjaxResult loginByWeixin(@RequestBody WxLoginInfo wxLoginInfo) {
        AjaxResult ajax = AjaxResult.success();
        String wxCode = wxLoginInfo.getWxCode();
        UserInfo userInfo = wxLoginInfo.getUserInfo();
        Map<String, String> wxAuth = wxAuth(wxCode);
        if (wxAuth == null || userInfo == null) {
            return AjaxResult.error("授权信息获取失败");
        }
        String openId = wxAuth.get("openId");
        String sessionKey = wxAuth.get("sessionKey");
        //WxMaPhoneNumberInfo phoneNoInfo = null;
        // 解密手机号
        //phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, wxLoginInfo.getEncryptedData(), wxLoginInfo.getIv());
        //WxMaConfigHolder.remove();//清理ThreadLocal
        SysUser user = userService.selectUserByOpenId(openId);
        String token = null;
        if (user == null) {
            //todo 暂定填写该值,后期待完善
            user = new SysUser();
            StringJoiner stj = new StringJoiner("", "YH", "");
            stj.add(sequenceFactory.generateOrderNum("JMT", 5));
            user.setUserCode(stj.toString());
            user.setUserName(sessionKey);
            user.setPassword(SecurityUtils.encryptPassword(openId));
            user.setOpenId(openId);
            user.setAvatar(userInfo.getAvatarUrl());
            user.setSessionKey(sessionKey);
            //user.setPhonenumber(phoneNoInfo.getPhoneNumber()); //被小程序禁止
            //添加设备号
            user.setTableNo(wxLoginInfo.getTableNo());
            //设定状态(第一次小程序授权)
            user.setLoginStatus("未授权");
            userService.insertUser(user);
            // 生成token值
            token = loginService.login(user.getUserName(), user.getOpenId());
        } else {
            //更改设备号(防止同一人换设备体验)
            userService.updateTableNoByOpenId(openId, wxLoginInfo.getTableNo());
            //更改授权状态(第二次VR端扫码)
            userService.updateLoginStatusByOpenId(openId, "已授权");
            //下次登录需要用到这个token值
            token = loginService.login(user.getUserName(), openId);
            user.setSessionKey(sessionKey);
        }
        ajax.put("token", token);
        ajax.put("userInfo", user);
        return AjaxResult.success(ajax);
    }

### 回答1: 以下是一个使用PHP编写的微信一键登录的示例代码: ```php <?php // 微信开放平台上获取的应用信息 $appid = 'your_appid'; $appsecret = 'your_appsecret'; // 获取微信授权用户的access_token和openid if(isset($_GET['code'])){ // 通过code换取access_token $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$_GET['code']."&grant_type=authorization_code"; $res = file_get_contents($url); $res = json_decode($res, true); $access_token = $res['access_token']; $openid = $res['openid']; // 获取用户信息 $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN"; $res = file_get_contents($url); $res = json_decode($res, true); $nickname = $res['nickname']; $headimgurl = $res['headimgurl']; // 将用户信息存储在session中 session_start(); $_SESSION['nickname'] = $nickname; $_SESSION['headimgurl'] = $headimgurl; // 跳转到登录成功页面 header("Location: login_success.php"); }else{ // 用户未授权,跳转到微信授权页面 $redirect_uri = urlencode("http://yourdomain.com/weixin_login.php"); $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; header("Location: ".$url); } ``` 以上代码实现了微信授权登录的基本流程。用户点击登录按钮后,会跳转到微信授权页面,用户确认授权后,会重定向到weixin_login.php页面,并携带授权code参数。通过code参数,可以获取用户的access_token和openid,进而获取用户信息。获取到用户信息后,可以将用户信息存储在session中,然后跳转到登录成功页面。 ### 回答2: PHP是一种常用的服务器端编程语言,可以用来实现各种网站和应用程序的功能。下面是一个简单的PHP代码示例,实现微信一键登录功能: 首先,需要在微信开放平台上注册一个应用,获取到AppID和AppSecret。 ```php <?php // 微信一键登录 function wechatLogin() { $code = $_GET['code']; // 从微信授权回调url参数中获取code $appId = 'your_app_id'; // 替换为你的AppID $appSecret = 'your_app_secret'; // 替换为你的AppSecret // 根据code获取access_token和openid $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appId . '&secret=' . $appSecret . '&code=' . $code . '&grant_type=authorization_code'; $response = file_get_contents($url); $data = json_decode($response, true); $accessToken = $data['access_token']; $openid = $data['openid']; // 使用access_token和openid获取用户信息 $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $accessToken . '&openid=' . $openid; $response = file_get_contents($url); $userInfo = json_decode($response, true); // 可以根据需要处理$userInfo数据,比如获取昵称、头像等信息 // 根据openid生成用户标识,用于登录验证 $userId = md5($openid); // 登录成功,可以执行相应的操作,比如保存用户信息到数据库 saveUserInfo($userId, $userInfo); // 将用户标识保存到session中,方便后续使用 $_SESSION['userId'] = $userId; // 跳转到登陆成功的页面 header('Location: success.php'); exit; } // 保存用户信息到数据库 function saveUserInfo($userId, $userInfo) { // 实现保存用户信息的代码,比如插入数据库或更新用户信息 // 根据需求进行相应的操作 } ?> ``` 以上代码通过获取微信授权回调url中的code参数,再通过code获取access_token和openid,最后使用access_token和openid获取用户信息。获取到用户信息后,可以根据需求进行相应的操作,比如保存用户信息到数据库。最后将用户标识保存到session中,方便后续使用。 请注意,以上代码是一个简单的示例,具体实现需要根据实际情况进行调整和完善。同时,为了确保安全性,可能还需要进行一些其他的安全性验证和操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值