Java 获取小程序openid(基于SpringBoot)
1.引入Request
封装依赖
<!--Request依赖-->
<dependency>
<groupId>com.github.kevinsawicki</groupId>
<artifactId>http-request</artifactId>
<version>6.0</version>
</dependency>
2.封装请求
可以在开发者后台获取AppId
和AppSecret
WxMiniConfig
public class WxMiniConfig {
public static String AppId = "";
public static String AppSecret="";
}
构建接口请求
WxOpenData
import com.github.kevinsawicki.http.HttpRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class WxOpenData {
@RequestMapping(value = "/WxOpenData")
public String getWxOpenData(@RequestParam(value = "js_code",required = true) String js_code){
Map<String, String> data = new HashMap<String, String>();
data.put("appid", WxMiniConfig.AppId);
data.put("secret", WxMiniConfig.AppSecret);
data.put("js_code", js_code);
data.put("grant_type", "authorization_code");
String response = HttpRequest.get("https://api.weixin.qq.com/sns/jscode2session").form(data).body();
//JSONObject obj= JSON.parseObject(response);//将json字符串转换为json对
return response.toString();
}
}
3.小程序端请求写法
wx.login({
success: res => {
wx.request({
url: 服务地址 + '/WxOpenData',
data: {
js_code: res.code
},
success: _res => {
console.log(_res);//打印返回的openid 等信息 ,可以JSON.parse()提取
},
fail: _res => {
}
})
}
})
4. SSL证书校验问题
sun.security.provider.certpath.SunCertPathBuilderException
Protocol handler initialization failed
可以自己下载SSL证书Tomcat
版,配置到Resource
目录下。
application.properties
配置证书部分内容如下所示
#server.ssl.key-store=classpath:atlab.pfx
server.ssl.key-store=classpath:coms.pfx
#证书密码,请修改为您自己证书的密码.
server.ssl.key-store-password=ARU3dlCp
#秘钥库类型
#server.ssl.key-store-type:PKCS12
server.ssl.key-store-type=JKS
之后重启后多请求几次即可恢复正常服务。
参考文档
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html