1.认证服务器,使公众号开发后可以调用该服务器的下的接口(js同)
@RestController
public class WeixinController {
private Logger logger = LoggerFactory.getLogger(WeixinController.class);
@GetMapping("")//(value = "/",produces = { "application/json;charset=utf-8" })//
public String getWxRequest(@RequestParam(required = false) String echostr,
@RequestParam(required = false) String signature,
@RequestParam(required = false) String timestamp,
@RequestParam(required =false) String nonce){
String token="weixin";
//1)将token、timestamp、nonce三个参数进行字典序排序
List<String> list=new ArrayList();
list.add(token);
list.add(timestamp);
list.add(nonce);
Collections.sort(list);
//2)将三个参数字符串拼接成一个字符串进行sha1加密
String sha1Hex = DigestUtils.sha1Hex(list.get(0) + list.get(1) + list.get(2));
logger.info("sha1Hex:{}",sha1Hex);
//将加密与signature比对,结果一致说明来自微信服务器,返回echostr
if (sha1Hex.equals(signature)){
return echostr;
}
return null;
}
}
js直接配置就可以
设置授权的网站
先开发自定义菜单模块,设置网页入口,然后进入网页开发(授权只是为了获取用户信息等)
2.获取用户access_token
String url=" https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
url= String.format(url,"wxd51c370ef340ace1","a47f52d802dca90063816c64b2f59aca");
//application/x-www-form-urlencoded
Connection.Response response = Jsoup.connect(url)
.ignoreContentType(true)
.header("Accept", "application/json, text/plain, */*")
// .header("Content-Type", "application/json;charset=UTF-8")
.method(Connection.Method.GET).execute();
String body = response.body();
JSONObject jsonObject = JSONObject.parseObject(body);
System.out.println(jsonObject);
=======微信网页开发
3.通过oauth2授权获取登录令牌access_token(不同于用户access_token)
/*通过这个页面授权*/
@GetMapping("/oauth")
public void oauth(HttpServletResponse response) throws IOException {
//配置域名不带http或者https===》shaofeng.free.idcfengye.com (~~~挂载域名后面的都可以授权)
//获取code
String url="https://open.weixin.qq.com/connect/oauth2/authorize?" +
"appid=%s" +
"&redirect_uri=%s" +
"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
url= String.format(url,"wxd51c370ef340ace1","http://shaofeng.free.idcfengye.com/getUserInfo");
//url是上面配置的授权url域名下的
//用户确认授权跳转到redirect_uri
response.sendRedirect(url);
}
@GetMapping("/getUserInfo")
public String getUserInfo(HttpServletRequest request) throws IOException{
String code = request.getParameter("code");
String url1="https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
url1= String.format(url1,"wxd51c370ef340ace1","a47f52d802dca90063816c64b2f59aca",code);
Connection.Response response1 = Jsoup.connect(url1)
.ignoreContentType(true)
.header("Accept", "application/json, text/plain, */*")
// .header("Content-Type", "application/json;charset=UTF-8")
.method(Connection.Method.POST).execute();
System.out.println(JSONObject.parseObject(response1.body()));
return JSONObject.parseObject(response1.body()).getString("access_token");
}