一、通过wx.login获取登录凭证(code)
首先快速建立了一个微信小程序开发工程,运行红框内代码,通过 wx.login 接口获得临时登录凭证 code 后,到开发者服务器调用接口完成登录流程。
wx.login({
success (res) {
console.log(res.code)
}
})
二、后端发送请求:
发送请求需要三步:
1.准备好发送GET请求的工具类:
这里推荐这篇文章,很简单。HttpClientUtil java工具_zhangzhenkeai的博客-CSDN博客
2. 获取自己的appID和SecretID
开发管理
选择开发设置,找到AppID和AppSecret
3.发送auth.code2Session登录凭证校验
package com.ling.findcar.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class GetOpenId {
private final String appId = "wxXXXXXXXXXXXXX";//小程序appID
private final String secretId = "XXXXXXXXXXXXXXXXXXXXXXX";//小程序appSecret
private final String url = "https://api.weixin.qq.com/sns/jscode2session";
public String getOpenId(String code) {
String requestUrl = url+"?appid="+appId+"&secret="+secretId+"&js_code="+code+"&grant_type=authorization_code";
System.out.println(requestUrl);
// String path = URLEncoder.encode(requestUrl,"utf-8");
String result = HttpClientUtil.doGet(requestUrl);
return result;
}
}
其中getOpenId函数的参数为第一步获取到的code.
运行后控制台输出为