# Spring Boot 微信小程序获取 openid 和 session_key

# 一、小程序端

    wx.login({
      success (res) {
        if (res.code) {
          console.log("res = " + res.code);
          //发起网络请求
          wx.request({
            url: 'http://localhost:8090/onLogin',
            data: {
              code: res.code
            },
            method: 'GET'
          })
        } else {
          console.log('登录失败!' + res.errMsg)
        }
      }
    })
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 二、spring boot 服务端

# 2.1 导入依赖

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.32</version>
        </dependency>

        <dependency>
            <groupId>com.github.kevinsawicki</groupId>
            <artifactId>http-request</artifactId>
            <version>6.0</version>
        </dependency>
1
2
3
4
5
6
7
8
9
10
11

# 2.2 java 代码

/**
  * 微信登陆,获取 openid 和 session_key
  *
  * @param code 登录凭证
  * @throws IOException
  */
@RequestMapping(value = "/onLogin")
public void wxLogin(@RequestParam("code") String code)  throws IOException {
    System.out.println("code = " + code);
    Map<String, String> data = new HashMap<String, String>();
    data.put("appid", "app_id");
    data.put("secret", "app_secret");
    data.put("js_code", 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);

    String openid = obj.getString("openid");
    String session_key = obj.getString("session_key");
    System.out.println("openid = " + openid);
    System.out.println("session_key = " + session_key);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 参考资料

微信官方文档-小程序登录

https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserInfo.html (opens new window)