【微信小程序】springboot后台获取用户的openid

openid可以标识一个用户,session_key会变,所以来获取一下openid。

openid不能在微信小程序中直接获取,需要后台发送请求到微信的接口,然后微信返回一个json格式的字符串到后台,后台处理之后,再返回到微信小程序。

发布的小程序需要https的域名,而测试的时候可以使用http。

小程序在app.js中,修改login()中的内容:

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if (res.code) {
          wx.request({
            url: ‘http://localhost:84/user/login‘,
            method: ‘POST‘,
            data: {
              code: res.code
            },
            header: {
              ‘content-type‘: ‘application/x-www-form-urlencoded‘
            },
            success(res) {
              console.log("openid:"+res.data.openid);
              if (res.data.openid != "" || res.data.openid!=null){
                // 登录成功
                wx.setStorageSync("openid", res.data.openid);//将用户id保存到缓存中
                wx.setStorageSync("session_key", res.data.session_key);//将session_key保存到缓存中
              }else{
                // 登录失败
                // TODO 跳转到错误页面,要求用户重试


                return false;
              }
            }
          })
        } else {
          console.log(‘获取用户登录态失败!‘ + res.errMsg)
        }
      }
    })

这里请求的http://localhost:84/user/login

后台的处理类:

package com.ft.feathertrade.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ft.feathertrade.entity.OpenIdJson;
import com.ft.feathertrade.utils.HttpUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
public class LoginHandler {

    private String appID = "";
    private String appSecret = "";

    @PostMapping("/user/login")
    public String userLogin(@RequestParam("code") String code) throws IOException {
        String result = "";
        try{//请求微信服务器,用code换取openid。HttpUtil是工具类,后面会给出实现,Configure类是小程序配置信息,后面会给出代码
            result = HttpUtil.doGet(
                    "https://api.weixin.qq.com/sns/jscode2session?appid="
                            + this.appID + "&secret="
                            + this.appSecret + "&js_code="
                            + code
                            + "&grant_type=authorization_code", null);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        ObjectMapper mapper = new ObjectMapper();
        OpenIdJson openIdJson = mapper.readValue(result,OpenIdJson.class);
        System.out.println(result.toString());
        System.out.println(openIdJson.getOpenid());
        return result;
    }

}

HttpUtil工具类:

package com.ft.feathertrade.utils;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.httpclient.HttpStatus;//此类需要添加maven依赖或jar包

/** 将此依赖添加到pom.xml中
 <dependency>
 <groupId>commons-httpclient</groupId>
 <artifactId>commons-httpclient</artifactId>
 <version>3.1</version>
 </dependency>
 **/

public class HttpUtil {

    public static String doGet(String urlPath, HashMap<String, Object> params)
            throws Exception {
        StringBuilder sb = new StringBuilder(urlPath);
        if (params != null && !params.isEmpty()) { // 说明有参数
            sb.append("?");

            Set<Entry<String, Object>> set = params.entrySet();
            for (Entry<String, Object> entry : set) { // 遍历map里面的参数
                String key = entry.getKey();
                String value = "";
                if (null != entry.getValue()) {
                    value = entry.getValue().toString();
                    // 转码
                    value = URLEncoder.encode(value, "UTF-8");
                }
                sb.append(key).append("=").append(value).append("&");
            }

            sb.deleteCharAt(sb.length() - 1); // 删除最后一个&
        }
        // System.out.println(sb.toString());
        URL url = new URL(sb.toString());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000); // 5s超时
        conn.setRequestMethod("GET");

        if (conn.getResponseCode() == HttpStatus.SC_OK) {// HttpStatus.SC_OK ==
            // 200
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            StringBuilder sbs = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sbs.append(line);
            }
            return sbs.toString();
        }

        return null;
    }
}

OpenIdJson的实体类:

【微信小程序】springboot后台获取用户的openid
package com.ft.feathertrade.entity;

public class OpenIdJson {
    private String openid;
    private String session_key;

    public String getOpenid() {
        return openid;
    }

    public void setOpenid(String openid) {
        this.openid = openid;
    }

    public String getSession_key() {
        return session_key;
    }

    public void setSession_key(String session_key) {
        this.session_key = session_key;
    }
}
View Code

 参考自:https://blog.csdn.net/qq_20372833/article/details/89597420

【微信小程序】springboot后台获取用户的openid

上一篇:android 保持菜单一直在底部的实现方法


下一篇:微信小程序:微信web开发阶段性学习总结