简单的微信验证登录(只有获取头像和名称还有openId的)

controller类:

package com.ruoyi.system.controller.api;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.TbUser;
import com.ruoyi.system.service.ITbUserService;
import com.ruoyi.system.toeknUnits.WxLoginUser;
import com.ruoyi.system.toeknUnits.WxTokenService;
import jdk.nashorn.internal.runtime.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

@RestController
@RequestMapping("/api")
public class ApiController {

    @Autowired
    private ITbUserService tbUserService;

    @Autowired
    private WxTokenService wxTokenService;

    //AppID
    final String appId = "";
    //密钥
    final String secret= "";

    @GetMapping("/getCode")
    @Logger(name = "根据Code 获取微信信息")
    public AjaxResult getCode(String Code){
        if (StringUtils.isBlank(Code)) {
            return AjaxResult.error("没有code");
        }
        String openId = null;
        String session_key = null;
        TbUser tbUserReturn = new TbUser();
        /**
         *  是否有 openid
         *  有openid  就返回 用户信息
         *  没有openid 就 返回 openid 给前段, 前段  调用  getUserinfo  返回信息给  后端  保存到数据库
         */
        try {
            URL url = new URL("https://api.weixin.qq.com/sns/jscode2session");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);

            String params = "appid="+ appId +"&secret="+ secret +"&js_code="+ Code+"&grant_type=authorization_code";
            OutputStream os = conn.getOutputStream();
            os.write(params.getBytes());
            os.flush();
            os.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            JSONObject jsonObject =  JSON.parseObject(response.toString());
            session_key = jsonObject.get("session_key").toString();
            openId = jsonObject.get("openid").toString();

        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }

        TbUser tbUser = new TbUser();
        tbUser.setOpenId(openId);
        List<TbUser> tbUsers = tbUserService.selectTbUserList(tbUser);
        tbUserReturn.setOpenId(openId);
        if(tbUsers.size() > 0 && tbUsers.get(0).getNickName() != null){  //数据库是否有此用户
            WxLoginUser wxLoginUser = new WxLoginUser();
            wxLoginUser.setUserId(tbUsers.get(0).getId());
            wxLoginUser.setNickName(tbUsers.get(0).getNickName());
            wxLoginUser.setOpenId(tbUsers.get(0).getOpenId());
            String token = wxTokenService.createToken(wxLoginUser);
            wxLoginUser.setToken(token);
            wxTokenService.refreshToken(wxLoginUser);
            tbUsers.get(0).setToken(token);
            return AjaxResult.success(tbUsers.get(0));
        }else if(tbUsers.size() > 0 && tbUsers.get(0).getNickName() == null){  //有此openID 但是没有授权
            return AjaxResult.success(tbUserReturn);
        }else if(tbUsers.size() == 0 ){
            return AjaxResult.success(tbUserReturn);
        }

        return  AjaxResult.error("error");
    }


    @PostMapping("/updateUserInfo")
    @Logger(name = "修改个人信息")
    public AjaxResult updateUserInfo(@RequestBody TbUser tbUser){
        int i = tbUserService.updateTbUser(tbUser);
        TbUser user = tbUserService.selectTbUserById(tbUser.getId());
        return  AjaxResult.success(user);
    }

    @PostMapping("/addUserInfo")
    @Logger(name = "添加个人信息")
    public AjaxResult addUserInfo(@RequestBody TbUser tbUser){
        int i = tbUserService.insertTbUser(tbUser);
        TbUser user = tbUserService.selectTbUserById(tbUser.getId());

        WxLoginUser wxLoginUser = new WxLoginUser();
        wxLoginUser.setUserId(user.getId());
        wxLoginUser.setNickName(user.getNickName());
        wxLoginUser.setOpenId(user.getOpenId());
        String token = wxTokenService.createToken(wxLoginUser);
        user.setToken(token);
        wxLoginUser.setToken(token);
        wxTokenService.refreshToken(wxLoginUser);
        return  AjaxResult.success(user);
    }

    @PostMapping("/getUserInfoByToken")
    @Logger(name = "根据token获取用户信息")
    public AjaxResult getUserInfoByToken(HttpServletRequest request){
        WxLoginUser wxUser = wxTokenService.getWxUser(request);
        TbUser user = tbUserService.selectTbUserById(wxUser.getUserId());
        return  AjaxResult.success(user);
    }

    @GetMapping("/test")
    public AjaxResult test(){

        return  AjaxResult.success("测试token");
    }


}

前端:

<template>
	<view>
		<!-- 我的 -->
		<u-navbar
			title="我的"
			:autoBack="false"
			leftIconSize="0"
			:placeholder="true"
			bgColor="#122977"
			:titleStyle="{color: '#fff', fontWeight: 'bold'}"
		>
		</u-navbar>
		
		<view>
			<view v-if="userInfo.id == 0 ||!userInfo" class="bg-fff headTitle" @click="getUserInfo">
				<view>
					<image src="../../static/logo.png" class="headImg" mode=""></image>
				</view>
				<view class="userName marginLeft-max">
					未登录
				</view>
			</view>
			
			<view v-else class="bg-fff headTitle">
				<view>
					<image :src="userInfo.avatarUrl" class="headImg" mode=""></image>
				</view>
				<view class="userName marginLeft-max">
					{{userInfo.nickName}}
				</view>
			</view>
			
			<view class="marginTop-max bg-fff">
				<view class="flex flex-between align-center line-color" style="padding: 12px 10px; font-size: 14px; "
				v-for="(item, index) in menuList" :key="index" @click="goMethod(item)"
				>
					<view class="flex align-center"  v-if="item.id != 2">
						<view>
							<u-icon :name="item.iconName" size="18" color="#122977"></u-icon>
						</view>
						<view class="marginLeft-middle">
							 {{item.name}}
						</view>
					</view>
					
					<u-button v-if="item.id == 2" :hoverStopPropagation="true" openType="contact" :hoverStartTime="1000000" size="mini" 
					:customStyle="{border: 'none', display: 'flex', justifyContent: 'start', position: 'relative', right: '9px'}">
						<view class="flex align-center">
							<view>
								<u-icon :name="item.iconName" size="18" color="#122977"></u-icon>
							</view>
							<view class="marginLeft-middle" style="font-size: 14px;">
								{{item.name}}
							</view>
						</view>
					</u-button>
					
					
					<view>
						<u-icon name="arrow-right"></u-icon>
					</view>
				</view>
			</view>
			
		</view>
		
		<u-popup :show="show" @close="show = false" @open="show = true" mode="center" 
		:customStyle="{borderRadius: '8px', padding: '15px'}">
			<view>
				<view style="text-align: center; font-weight: bold; font-size: 17px;">微信授权</view>
				<view class="marginTop-middle">
					友好的区别用户在平台上的信息
				</view>
				
				<u-button 
				@click="addUserInfo" 
				type="primary" 
				:customStyle="{width: '50%', marginTop: '10px'}">
					确认授权 
				</u-button>
			</view>
		</u-popup>
		
		<tabbarInfo :current="4"></tabbarInfo>
	</view>
</template>

<script>
	import tabbarInfo from "../../components/tabbar/tabbar.vue"
	import { loginByCode, addUserInfo, getUserInfoByToken, test } from "../../config/api.js"
	export default {
		data() {
			return {
				show: false,
				userInfo: {
					id: 0,
					avatarUrl: "",
					nickName: "",
					openId: ""
				},
				menuList: [
					{
						id: 1,
						iconName: "info-circle",
						name: "关于我们",
						toPath: ""
					},{
						id: 2,
						iconName: "kefu-ermai",
						name: "联系客服",
						toPath: ""
					},{
						id: 3,
						iconName: "fingerprint",
						name: "隐私政策",
						toPath: ""
					}
				]
			}
		},
		components: {
			tabbarInfo
		},
		onShow() {
			let that = this;
			let token = uni.getStorageSync("token");
			if(!token){
				
			}else{
				that.getUserInfoByToken();
			}
		},
		methods: {
			goMethod(event){
				let that = this;
				// 测试取消授权
				if(event.id == 4){
					uni.openSetting({
						success:function(res){
							console.log(res.authSetting);
						}
					})
				}
				
				test().then(res => {
					console.log(res);
				})
				
			},
			getUserInfoByToken(){
				let that = this;
				getUserInfoByToken().then(res => {
					that.userInfo = res.data;
				})
			},
			getUserInfo(){
				let that = this;
				uni.login({
					"provider": "weixin",
					"onlyAuthorize": true, 
					success: function(event){
						const {code} = event
						loginByCode(code).then(res => {
								if(res.data.nickName){
									that.userInfo = res.data;
									uni.setStorageSync("token", res.data.token)
								}else{
									that.userInfo.openId = res.data.openId;
									that.show = true;
								}
						})
					},
					fail: function (err) {
						// 登录授权失败  
						// err.code是错误码
						console.log("授权错误", err.code);
					}
				})
			},
			addUserInfo(){
				let that = this;
				wx.getUserProfile({
					desc: "友好的区别用户在平台上的信息",
					success:function(resd){
						addUserInfo({
							"nickName": resd.userInfo.nickName,
							"avatarUrl": resd.userInfo.avatarUrl,
							"openId": that.userInfo.openId
						}).then(res => {
							that.userInfo = res.data;
							uni.setStorageSync("token", res.data.token)
							that.show = false;
							uni.showToast({
								title: "授权成功",
								duration: 1000,
								icon: "none"
							})
						})
						
					},
					fail:function(resd){
						console.log(resd);
						uni.showToast({
							title: "授权失败",
							duration: 1000,
							icon: "none"
						})
					}
				})
			},
		}  
	}
</script>

<style lang="scss">
	page{
		background-color: #f9f9f9;
	}
	.headTitle{
		height: 60px;
		line-height: 60px;
		display: flex;
		padding: 20px;
	}
	.headImg{
		width: 50px;
		height: 50px;
		border-radius: 25px;
	}
	.userName{
		font-weight: bold;
		font-size: 17px;
		position: relative;
		bottom: 4px;
	}
</style>

api.js

const http = uni.$u.http

export const loginByCode = (params) => http.get(`/getCode?Code=${params}`)

export const addUserInfo = (data) => http.post(`/addUserInfo`, data)

export const getUserInfoByToken = () => http.post(`/getUserInfoByToken`)

export const test = (params) => http.get(`/test`)

request.js

// 此vm参数为页面的实例,可以通过它引用vuex中的变量
module.exports = (vm) => {
    // 初始化请求配置
    uni.$u.http.setConfig((config) => {
        /* config 为默认全局配置*/
        config.baseURL = 'http://127.0.0.1:8080/api'; /* 根域名 */
        return config
    })
	
	// 请求拦截
	uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
	    // 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
		
		// if(config.url.search("/getCode") === -1){
		config.header.Authorization = 'tf: ' + uni.getStorageSync("token")
		// }
		
	    config.data = config.data || {}
	    return config 
	}, config => { // 可使用async await 做异步操作
	    return Promise.reject(config)
	})
	
	// 响应拦截
	uni.$u.http.interceptors.response.use((response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/
		const data = response.data

		// 自定义参数
		const custom = response.config?.custom
		if(data.code === 401){
			uni.showToast({
				title: "请登录",
				duration:1000,
				icon: "none"
			})
			uni.switchTab({
				url: "/pages/mine/mine"
			})
		}else if (data.code !== 200) { 
			uni.showToast({
				title: "错误",
				duration:500,
				icon: "error"
			})
		}
		
		return data.data === undefined ? {} : data
	}, (response) => { 
		// 对响应错误做点什么 (statusCode !== 200)
		return Promise.reject(response)
	})
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我不是码神(dn)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值