用户授权后获取code,j将code传给后台用来获取openid;
后台获取openid真的各种乱七八糟的报错,明明代码也不难,关键要细心。还是直接上代码吧。
1.前端获取code并传给后台;
wx.login({
success: res => {
// 获取到用户的 code 之后:res.code
console.log("用户的code:" + res.code);
if(res.code){
wx.request({
url: 'http://localhost:8080/getopenid',
data:{
code: res.code,//获取openid的话 需要向后台传递code,利用code请求api获取openid
}
})
}
}
)}
2.后台使用的springboot+mybatisplus框架
spring访问外部接口获取信息,这里访问外部接口我是采用RestTemplate方法,这个方法是最简单的,因为springboot自带RestTemplate,不需要额外导入依赖
(1)创建一个config包在包下创建一个config类
(2)RestTemplateconfig 类
顺便一提:Ail+回车 快捷键导包
package com.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateconfig {
@Autowired
RestTemplateconfig restTemplate;
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(5000);//单位为ms
factory.setConnectTimeout(5000);//单位为ms
return factory;
}
}
(3)写action层
/*获取openid*/
@RequestMapping("/getopenid")
public Object getopenid(String code){
Object object= restTemplate.getForObject("https://api.weixin.qq.com/sns/jscode2session?appid=wxe81c709da39edd23&secret=9198d799524ecd032087a5313fc18251&js_code=" +code + "&grant_type=authorization_code",String.class);
return object;
}