微信小程序使用code换openid的方法(JAVA、SpringBoot)

前端之家收集整理的这篇文章主要介绍了微信小程序使用code换openid的方法(JAVA、SpringBoot)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

微信小程序序的代码提示,使用code换取openid,但官方文档中没有给出进一步的说明。

换取openid的要点:由于安全的原因,必须由自己小程序的服务器端完成。知道了这个要点,实现起来就简单了,服务器端写一个RestController,接收code参数,使用httpclient向微信的服务端换openid就行了。

代码使用了SpringBoot,不会也不难理解。主要代码如下:

  1. package com.wallimn.iteye.sp.asset.common.controller;
  2.  
  3. import java.util.Map;
  4.  
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.beans.factory.annotation.Value;
  8. import org.springframework.web.bind.annotation.RequestBody;
  9. annotation.RequestMapping;
  10. annotation.RequestMethod;
  11. annotation.RequestParam;
  12. annotation.RestController;
  13.  
  14. import com.fasterxml.jackson.databind.ObjectMapper;
  15. import com.wallimn.iteye.sp.asset.common.util.AesUtil;
  16. import com.wallimn.iteye.sp.asset.common.util.HttpUtil;
  17.  
  18. @RestController
  19. @RequestMapping("/api/wx")
  20. public class WeixinController {
  21.  
  22. private static Logger log = LoggerFactory.getLogger(WeixinController.class);
  23.  
  24. @Value("${wx.appId}")
  25. private String appId;
  26.  
  27. ${wx.appSecret}")
  28. private String appSecret;
  29.  
  30. ${wx.grantType}")
  31. private String grantType;
  32. // wx.grantType=authorization_code
  33.  
  34. ${wx.requestUrl}")
  35. private String requestUrl;
  36. // wx.requestUrl=https://api.weixin.qq.com/sns/jscode2session
  37.  
  38. "/session")
  39. public Map<String,Object> getSession(@RequestParam(required = true) String code) {
  40. return this.getSessionByCode(code);
  41. }
  42.  
  43. @SuppressWarnings("unchecked")
  44. private Map<String,Object> getSessionByCode(String code) {
  45. String url = this.requestUrl + "?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type="
  46. + grantType;
  47. // 发送请求
  48. String data = HttpUtil.get(url);
  49. log.debug("请求地址:{}",url);
  50. log.debug("请求结果:{}",data);
  51. ObjectMapper mapper = new ObjectMapper();
  52. Map<String,Object> json = null;
  53. try {
  54. json = mapper.readValue(data,Map.class);
  55. } catch (Exception e) {
  56. e.printStackTrace();
  57. }
  58. // 形如{"session_key":"6w7Br3JsRQzBiGZwvlZAiA==","openid":"oQO565cXXXXXEvc4Q_YChUE8PqB60Y"}的字符串
  59. return json;
  60. }
  61. }

用到了一个httpclient封闭的工具类,代码如下:

  1. package com.wallimn.iteye.sp.asset.common.util;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.net.URI;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. Map;
  10.  
  11. import org.apache.http.HttpResponse;
  12. import org.apache.http.NameValuePair;
  13. import org.apache.http.client.HttpClient;
  14. import org.apache.http.client.entity.UrlEncodedFormEntity;
  15. import org.apache.http.client.methods.HttpGet;
  16. import org.apache.http.client.methods.HttpPost;
  17. import org.apache.http.entity.StringEntity;
  18. import org.apache.http.impl.client.HttpClientBuilder;
  19. import org.apache.http.message.BasicNameValuePair;
  20.  
  21. public HttpUtil {
  22.  
  23. private static final String Charset = "utf-8";
  24.  
  25.  
  26. /**
  27. * 发送请求,如果失败,会返回null
  28. * @param url
  29. * @param map
  30. * @return
  31. */
  32. public static String post(String url,Map<String,0);">String> map) {
  33. // 处理请求地址
  34. try {
  35. HttpClient client = HttpClientBuilder.create().build();
  36. URI uri = new URI(url);
  37. HttpPost post = new HttpPost(uri);
  38.  
  39. // 添加参数
  40. List<NameValuePair> params = new ArrayList<NameValuePair>();
  41. for (String str : map.keySet()) {
  42. params.add(new BasicNameValuePair(str,map.get(str)));
  43. }
  44. post.setEntity(new UrlEncodedFormEntity(params,Charset));
  45. // 执行请求
  46. HttpResponse response = client.execute(post);
  47.  
  48. if (response.getStatusLine().getStatusCode() == 200) {
  49. // 处理请求结果
  50. StringBuffer buffer = new StringBuffer();
  51. InputStream in = null;
  52. try {
  53. in = response.getEntity().getContent();
  54. BufferedReader reader = new BufferedReader(new InputStreamReader(in,Charset));
  55. String line = null;
  56. while ((line = reader.readLine()) != null) {
  57. buffer.append(line);
  58. }
  59.  
  60. } catch (Exception e) {
  61. e.printStackTrace();
  62. } finally {
  63. // 关闭
  64. if (in != null)
  65. try {
  66. in.close();
  67. } catch (Exception e) {
  68. e.printStackTrace();
  69. }
  70. }
  71.  
  72. return buffer.toString();
  73. } else {
  74. null;
  75. }
  76. } catch (Exception e1) {
  77. e1.printStackTrace();
  78. }
  79. null;
  80.  
  81. }
  82.  
  83. @H_1_301@ * 发送请求,如果失败会返回null
  84. * @param str
  85. String str) {
  86. new HttpPost(uri);
  87. post.setEntity(new StringEntity(str,"utf-8"));
  88. in.close();
  89. }
  90.  
  91. catch (Exception e) {
  92. e.printStackTrace();
  93. }
  94. * 发送GET方式的请求,并返回结果字符串。
  95. * <br>
  96. * 时间:2017年2月27日,作者:http://wallimn.iteye.com
  97. * @return 如果失败,返回为null
  98. String get(String url) {
  99. new URI(url);
  100. HttpGet get = new HttpGet(uri);
  101. HttpResponse response = client.execute(get);
  102. 200) {
  103. finally {
  104. null;
  105.  
  106. }
  107. }

小程序中,使用wx.request(url:'https://域名/api/wx/session',....),就可以拿到一个JSON对象,其中有openid。

猜你在找的Springboot相关文章