微信登录接口提交

This commit is contained in:
linfeng 2022-08-18 12:50:50 +08:00
parent a53aeed91a
commit c5136354ca
10 changed files with 317 additions and 77 deletions

View File

@ -0,0 +1,172 @@
package io.linfeng.common.utils;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author linfeng
* @date 2022/8/18 10:12
*/
public class HttpRequest {
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数请求参数应该是 name1=value1&name2=value2 的形式
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数请求参数应该是 name1=value1&name2=value2 的形式
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param, String keyValue) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("api-key", keyValue);
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "UTF-8");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
//out = new PrintWriter(conn.getOutputStream());
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
public static String generateOrderId(){
String keyup_prefix=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String keyup_append= String.valueOf(new Random().nextInt(899999)+100000);
String pay_orderid=keyup_prefix+keyup_append;//订单号
return pay_orderid;
}
public static String generateTime(){
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
}
public static String md5(String str) throws NoSuchElementException {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes("UTF-8"));
byte[] byteDigest = md.digest();
int i;
//字符数组转换成字符串
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < byteDigest.length; offset++) {
i = byteDigest[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
// 32位加密
return buf.toString();//toUpperCase
// 16位的加密
//return buf.toString().substring(8, 24).toUpperCase();
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
}

View File

@ -64,5 +64,7 @@ public interface AppUserService extends IService<AppUserEntity> {
AppPageUtils follow(Integer page, AppUserEntity user);
AppUserInfoResponse findUserInfoById(Integer uid, AppUserEntity user);
Integer miniWxLogin(WxLoginForm form);
}

View File

@ -15,20 +15,20 @@ package io.linfeng.modules.admin.service.impl;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.linfeng.common.exception.LinfengException;
import io.linfeng.common.response.*;
import io.linfeng.common.utils.*;
import io.linfeng.modules.admin.entity.PostEntity;
import io.linfeng.modules.admin.entity.SystemEntity;
import io.linfeng.modules.admin.service.*;
import io.linfeng.modules.app.dao.FollowDao;
import io.linfeng.modules.app.entity.FollowEntity;
import io.linfeng.modules.app.form.AddFollowForm;
import io.linfeng.modules.app.form.AppUserUpdateForm;
import io.linfeng.modules.app.form.SendCodeForm;
import io.linfeng.modules.app.form.SmsLoginForm;
import io.linfeng.modules.app.form.*;
import io.linfeng.modules.app.service.FollowService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -43,6 +43,7 @@ import javax.servlet.http.HttpServletRequest;
@Service
@Slf4j
public class AppUserServiceImpl extends ServiceImpl<AppUserDao, AppUserEntity> implements AppUserService {
@ -61,6 +62,10 @@ public class AppUserServiceImpl extends ServiceImpl<AppUserDao, AppUserEntity> i
@Autowired
private FollowDao followDao;
@Autowired
private SystemService systemService;
@Override
public PageUtils queryPage(Map<String, Object> params) {
QueryWrapper<AppUserEntity> queryWrapper=new QueryWrapper<>();
@ -266,6 +271,54 @@ public class AppUserServiceImpl extends ServiceImpl<AppUserDao, AppUserEntity> i
return response;
}
@Override
public Integer miniWxLogin(WxLoginForm form) {
SystemEntity system = systemService.lambdaQuery().eq(SystemEntity::getConfig, "miniapp").one();
//小程序唯一标识 (在微信小程序管理后台获取)
String appId = system.getValue();
//小程序的 app secret (在微信小程序管理后台获取)
String secret = system.getExtend();
//授权必填
String grant_type = "authorization_code";
//https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
//1向微信服务器 使用登录凭证 code 获取 session_key openid
//请求参数
String params = "appid=" + appId + "&secret=" + secret + "&js_code=" + form.getCode() + "&grant_type=" + grant_type;
//发送请求
String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
//解析相应内容转换成json对象
JSONObject json =JSON.parseObject(sr);
//用户的唯一标识openId
String openId = (String) json.get("openid");
//根据openId获取数据库信息 判断用户是否登录
AppUserEntity user = this.lambdaQuery().eq(AppUserEntity::getOpenid, openId).one();
if(ObjectUtil.isNotNull(user)){
//已登录用户
if(user.getStatus()==1){
throw new LinfengException("该账户已被禁用");
}
return user.getUid();
}else{
//新注册用户
//注册
AppUserEntity appUser=new AppUserEntity();
appUser.setGender(0);
appUser.setAvatar(form.getAvatar());
appUser.setUsername(form.getUsername());
appUser.setCreateTime(DateUtil.nowDateTime());
appUser.setUpdateTime(DateUtil.nowDateTime());
appUser.setOpenid(openId);
List<String> list=new ArrayList<>();
list.add("新人");
appUser.setTagStr(JSON.toJSONString(list));
baseMapper.insert(appUser);
AppUserEntity users=this.lambdaQuery().eq(AppUserEntity::getOpenid,openId).one();
return users.getUid();
}
}
private Integer getTotalNum() {
return this.lambdaQuery().select(AppUserEntity::getUid).count();

View File

@ -15,6 +15,7 @@ import io.linfeng.common.response.AppUserInfoResponse;
import io.linfeng.common.response.AppUserResponse;
import io.linfeng.common.utils.AppPageUtils;
import io.linfeng.common.utils.R;
import io.linfeng.common.validator.ValidatorUtils;
import io.linfeng.modules.admin.entity.AppUserEntity;
import io.linfeng.modules.admin.service.AppUserService;
import io.linfeng.modules.app.annotation.Login;
@ -78,6 +79,28 @@ public class AppLoginController {
return R.ok(map);
}
/**
* 微信小程序登录
*/
@PostMapping("/miniWxlogin")
@ApiOperation("手机验证码登录")
public R miniWxLogin(@RequestBody WxLoginForm form){
//用户登录
Integer userId = appUserService.miniWxLogin(form);
//生成token
String token = jwtUtils.generateToken(userId);
Map<String, Object> map = new HashMap<>();
map.put("token", token);
map.put("expire", jwtUtils.getExpire());
return R.ok(map);
}
@Login
@GetMapping("/userInfo")

View File

@ -12,6 +12,10 @@
package io.linfeng.modules.app.controller;
import io.linfeng.common.utils.R;
import io.linfeng.modules.admin.entity.SystemEntity;
import io.linfeng.modules.admin.service.SystemService;
import io.linfeng.modules.sys.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@ -23,13 +27,15 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("app/system")
public class AppSystemController {
public class AppSystemConfigController {
@Autowired
private SystemService systemService;
@GetMapping("/miniConfig")
public R miniConfig(){
String value="";
return R.ok().put("intro",value);
SystemEntity system = systemService.lambdaQuery().eq(SystemEntity::getConfig, "miniapp").one();
return R.ok().put("logo",system.getIntro());
}
}

View File

@ -23,9 +23,6 @@ import javax.validation.constraints.NotBlank;
* code: loginCode,
* username: userInfo.nickName,
* avatar: userInfo.avatarUrl,
* province: userInfo.province,
* city: userInfo.city,
* gender: userInfo.gender
*/
@Data
@ApiModel(value = "微信登录表单")
@ -43,13 +40,4 @@ public class WxLoginForm {
@NotBlank(message="头像不能为空")
private String avatar;
@ApiModelProperty(value = "省份")
private String province;
@ApiModelProperty(value = "城市")
private String city;
@ApiModelProperty(value = "性别")
private Integer gender;
}

View File

@ -53,7 +53,7 @@
"appid" : "wx8068e1172da3e9d5",
"setting" : {
"urlCheck" : false,
"es6" : true,
"es6" : false,
"minified" : true
},
"usingComponents" : true,

View File

@ -53,52 +53,50 @@
},
getCode() {
let phoneCodeVerification = /^[1][3-9][0-9]{9}$/;
if(this.form.mobile==''){
if (this.form.mobile == '') {
this.$u.toast('请输入手机号');
}else if(!phoneCodeVerification.test(this.form.mobile)){
} else if (!phoneCodeVerification.test(this.form.mobile)) {
this.$u.toast('请输入规范的手机号');
}else{
if (this.$refs.uCode.canGetCode) {
//
uni.showLoading({
title: '正在获取验证码'
})
this.$H.post("user/sendSmsCode", {
mobile: this.form.mobile
}).then(res => {
if (res.code == 0) {
uni.hideLoading();
this.$refs.uCode.start();
this.$u.toast(res.msg);
}
})
} else {
this.$u.toast('倒计时结束后再发送');
}
if (this.$refs.uCode.canGetCode) {
//
uni.showLoading({
title: '正在获取验证码'
})
this.$H.post("user/sendSmsCode", {
mobile: this.form.mobile
}).then(res => {
if (res.code == 0) {
uni.hideLoading();
this.$refs.uCode.start();
this.$u.toast(res.msg);
}
})
} else {
this.$u.toast('倒计时结束后再发送');
}
}
},
end() {
},
start() {
}
end() {},
start() {}
}
}
</script>
<style lang="scss" scoped>
.login-register{
.login-register {
padding: 20rpx 50rpx;
}
.button-login{
.button-login {
margin-top: 100rpx;
}
.title{
.title {
font-size: 40rpx;
font-weight: 600;
margin-bottom: 50rpx;

View File

@ -23,49 +23,47 @@
this.getSysInfo();
},
methods: {
goBack(){
goBack() {
uni.reLaunch({
url: '/pages/index/index'
});
},
getSysInfo() {
this.$H.get("system/miniConfig").then(res => {
this.logo = res.result.intro;
this.logo = res.logo;
})
},
async login() {
uni.showLoading({
mask: true,
title: '登录中'
title: '正在登陆'
});
let that = this;
var that = this;
let userInfo = await this.getUserProfile();
let loginCode = await this.getLoginCode();
// console.log('========>', JSON.stringify(userInfo))
that.$H.post('user/miniWxLogin', {
code: loginCode,
let code = await this.getLoginCode();
that.$H.post('user/miniWxlogin', {
code: code,
username: userInfo.nickName,
avatar: userInfo.avatarUrl,
province: userInfo.province,
city: userInfo.city,
gender: userInfo.gender
}).then(res2 => {
if (res2.code === 0) {
}).then(res => {
if (res.code === 0) {
uni.setStorageSync("hasLogin", true);
uni.setStorageSync("token", res2.token);
uni.setStorageSync("token", res.token);
uni.switchTab({
url: '/pages/index/index'
});
that.getUserInfo();
uni.hideLoading();
}
uni.hideLoading();
})
},
getUserInfo() {
this.$H.get("user/userInfo").then(res => {
uni.setStorageSync("userInfo", res.result)
@ -118,10 +116,10 @@
color: #999;
margin-bottom: 50rpx;
}
.login .txt3 {
color: #8c8c8c;
margin-bottom: 90rpx;
margin-top: 30rpx;
text-align: center;
}
</style>

View File

@ -3,12 +3,12 @@ const shareH5Url = "https://www.linfeng.tech/#/"; //H5分享路径
//本地环境配置
// const baseUrl = "localhost:8080";
// const domain = 'http://' + baseUrl + "/app/";
const baseUrl = "localhost:8080";
const domain = 'http://' + baseUrl + "/app/";
//线上环境配置
const baseUrl = "wxapi.linfeng.tech";
const domain = 'https://' + baseUrl + "/app/";
// const baseUrl = "wxapi.linfeng.tech";
// const domain = 'https://' + baseUrl + "/app/";
export default {