流程
小程序登录文档

登录流程时序(详细查看,小程序就是前端,开发者服务器就是后端)

调用说明:

由前端发送请求获取临时登录凭证code,之后传递给后端,后端发送含appid、secret和code的请求给微信接口服务请求

获取到用户的openid用户唯一标识,即登陆成功,之后可将其存入数据库中
代码实现
这里使用hutool工具包发送http请求
hutool发送Http请求-HttpRequest
使用 hutool 工具包发送 HTTP 请求
依赖:
<!--Hutool-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.16</version>
</dependency>
yaml配置:
#微信支付
wechat-payment:
#微信小程序设置
wechat-mini-app:
#微信小程序APP ID
app-id: "xxxx"
#微信小程序APP SECRET
app-secret: "xxxxx"
代码
/**
* @author 徐楠
* @date 2022/3/5 11:04
* @version 1.0
*/
package org.sdyspx.stateartexam.service;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class WechatUserService {
/**
* 微信支付小程序APP ID
*/
@Value("${wechat-payment.wechat-mini-app.app-id}")
String WECHAT_MINI_APP_APP_ID;
/**
* 微信支付小程序APP SECRET
*/
@Value("${wechat-payment.wechat-mini-app.app-secret}")
String WECHAT_MINI_APP_APP_SECRET;
/**
* 用户唯一标识
*
* @param code 临时登录凭证 code
* @return 用户唯一标识
*/
public String getUserWechatOpenId(String code) {
String url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JS_CODE&grant_type=authorization_code";
url = url.replace("APPID", WECHAT_MINI_APP_APP_ID);
url = url.replace("SECRET", WECHAT_MINI_APP_APP_SECRET);
url = url.replace("JS_CODE", code);
//网络请求
String httpExecuteResult = HttpRequest.get(url).execute().body();
JSONObject jsonObject = new JSONObject(httpExecuteResult);
//获取错误代码(有可能不存在)
int errCode = jsonObject.get("errcode") == null ? 0 : (Integer) jsonObject.get("errcode");
if (errCode == 0) {
return (String) jsonObject.get("openid");
} else {
return null;
}
}
}
6754

被折叠的 条评论
为什么被折叠?



