uniapp微信小程序投票系统实战 (SpringBoot2+vue3.2+element plus ) -小程序微信用户登录实现

锋哥原创的uniapp微信小程序投票系统实战:

uniapp微信小程序投票系统实战课程 (SpringBoot2+vue3.2+element plus ) ( 火爆连载更新中... )_哔哩哔哩_bilibiliuniapp微信小程序投票系统实战课程 (SpringBoot2+vue3.2+element plus ) ( 火爆连载更新中... )共计21条视频,包括:uniapp微信小程序投票系统实战课程 (SpringBoot2+vue3.2+element plus ) ( 火爆连载更新中... )、第2讲 投票项目后端架构搭建、第3讲 小程序端 TabBar搭建等,UP主更多精彩视频,请关注UP账号。icon-default.png?t=N7T8https://www.bilibili.com/video/BV1ea4y137xf/application.yml加上小程序登录需要的参数,小伙伴们可以登录小程序后台管理,获取到自己的参数

weixin:
  jscode2sessionUrl: https://api.weixin.qq.com/sns/jscode2session
  appid: 改成你的
  secret: 改成你的

定义Properties属性类来映射上面的配置

package com.java1234.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 微信小程序配置文件
 * @author java1234_小锋
 * @site www.java1234.com
 * @company 南通小锋网络科技有限公司
 * @create 2022-01-08 17:56
 */
@Component
@ConfigurationProperties(prefix = "weixin")
@Data
public class WeixinProperties {

    private String jscode2sessionUrl; // 登录凭证校验请求地址

    private String appid; // 小程序 appId

    private String secret; // 小程序 appSecret


}
/**
 * 微信用户登录
 * @return
 */
@RequestMapping("/wxlogin")
public R wxLogin(@RequestBody WxUserInfo wxUserInfo){
    String jscode2sessionUrl=weixinProperties.getJscode2sessionUrl()+"?appid="+weixinProperties.getAppid()+"&secret="+weixinProperties.getSecret()+"&js_code="+wxUserInfo.getCode()+"&grant_type=authorization_code";
    System.out.println(jscode2sessionUrl);
    String result = httpClientUtil.sendHttpGet(jscode2sessionUrl);
    System.out.println(result);
    JSONObject jsonObject= JSON.parseObject(result);
    String openid = jsonObject.get("openid").toString();
    System.out.println(openid);
    // 插入用户到数据库  假如说 用户不存在 我们插入用户  如果用户存在 我们更新用户
    WxUserInfo resultWxUserInfo = wxUserInfoService.getOne(new QueryWrapper<WxUserInfo>().eq("openid", openid));
    if(resultWxUserInfo==null){
        System.out.println("不存在 插入用户");
        wxUserInfo.setOpenid(openid);
        wxUserInfo.setRegisterDate(new Date());
        wxUserInfo.setLastLoginDate(new Date());
        wxUserInfoService.save(wxUserInfo);
    }else{
        System.out.println("存在 更新用户");
        resultWxUserInfo.setLastLoginDate(new Date());
        wxUserInfoService.updateById(resultWxUserInfo);
    }
    if(resultWxUserInfo!=null && resultWxUserInfo.getStatus().equals("1")){ // 被禁用
        return R.error(400,"用户被禁用,具体请联系管理员!");
    }else{
        // 利用jwt生成token返回到前端
        String token = JwtUtils.createJWT(openid, wxUserInfo.getNickName(), JwtConstant.JWT_TTL);
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("token",token);
        resultMap.put("openid",openid);
        return R.ok(resultMap);
    }
}

设置appId

requestUtils封装:

// 同时发送异步代码的次数
let ajaxTimes=0;

// 定义公共的url
const baseUrl="http://localhost:8866";

/**
 * 返回baseUrl
 */
export const getBaseUrl=()=>{
  return baseUrl;
}

/**
 * 后端请求工具类
 * @param {*} params 请求参数
 */
export const requestUtil=(params)=>{
 
   let header={...params.header};
 
    // 拼接header 带上token
    header["token"]=uni.getStorageSync("token");

    ajaxTimes++;
	
     // 显示加载中 效果
    wx.showLoading({
      title: "加载中",
      mask: true
    });

    var start = new Date().getTime();

    // 模拟网络延迟加载
    while(true)  if(new Date().getTime()-start > 1000*1) break;

  return new Promise((resolve,reject)=>{
    wx.request({
     ...params,
     header:header,
     url:baseUrl+params.url,
     success:(result)=>{
       resolve(result.data);
     },
     fail:(err)=>{
		 uni.showToast({
			icon:'error',
		 	title:'连接服务器失败',
			duration:3000
		 })
       reject(err);
     },
     complete:()=>{
      ajaxTimes--;
      if(ajaxTimes===0){
        //  关闭正在等待的图标
        wx.hideLoading();
      }
     }
    });
  })
}

App.vue

<script>
	import {requestUtil} from "./utils/requestUtil.js"
	export default {
		onLaunch: function() {
			console.log('App Launch')
			wx.login({
				timeout: 5000,
				success:(res)=>{
					this.wxlogin(res.code);
				}
			});
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods:{
			/**
			 * 请求后端获取用户token
			 * @param {} code 
			 */
			async wxlogin(code){
				console.log("code="+code)
				// 发送请求 获取用户的token
				const result=await requestUtil({url:"/user/wxlogin",data:{code:code},method:"post"});
				console.log("token="+result.token);
				console.log("openid="+result.openid);
				if(result.code==0){
					console.log("登录成功")
					uni.setStorageSync("token",result.token);
					uni.setStorageSync("openid",result.openid);
				}else{
					console.log("登录失败,报错信息:"+result.msg);
					uni.showToast({
							icon:'error',
							title:result.msg,
							duration:3000
					})
				}
			}
		}
	}
</script>

<style>
	/*每个页面公共css */
	body,page{
		background-color: #f4f5f7;
	}
</style>

猜你喜欢

转载自blog.csdn.net/caoli201314/article/details/135416180