基本概念
微信小程序-登录凭证校验:通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程。
微信小程序API
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
源代码
package club.zstuca.myzstu.provider;
import club.zstuca.myzstu.consts.Consts;
import club.zstuca.myzstu.httpclient.HttpClientUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
* @Author ShenTuZhiGang
* @Version 1.0.0
* @Date 2020-02-10 10:59
*/
@Component
public class WeChatProvider {
@Value("${wechat.login.appid}")
private String APPID ;
@Value("${wechat.login.secret}")
private String SECRET;
private final String WX_URL = "https://api.weixin.qq.com/sns/jscode2session";
@Value("${wechat.login.grant-type}")
private String grantType;
public String getOpenId(String code) {
String openid = "";
Map<String, String> header = new HashMap<>();
header.put("User-Agent", Consts.AGENT);
Map<String, String> params = new HashMap<>();
params.put("appid", APPID);
params.put("secret", SECRET);
params.put("js_code", code);
params.put("grant_type", grantType);
String response = HttpClientUtils.doGetRequest(WX_URL, header, params);
System.out.println(response);
System.out.println(APPID);
openid = JSONObject.parseObject(response).getString("openid");
System.out.println(openid);
return openid;
}
}