java后台获取小程序accesstoken和openid

1.添加依赖

 <dependency>
 <groupId>commons-httpclient</groupId>
 <artifactId>commons-httpclient</artifactId>
 <version>3.1</version>
 </dependency>

2.添加工具类(无需修改)

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包
/**
 * 获取openid需要用到的工具类
 */
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;
    }
}

3.添加实体类,将openid和session_key封装起来

/**
 * 获取openid和session_key
 */
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;
    }
}

2.java后台向小程序接口发起请求,获取token和openid
note:
由于我们小程序前端在获取到token和openid后就直接将其都存储到小程序的缓存storage中了,所以避免了token号需要定时更新的问题。

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录后,立即获取小程序用户的基本信息:token及其有效时长,openid(唯一标识一位用户)。。。
 */
@RestController
public class LoginController {

    public static Map<String, String> LOGININFO;//保存当前用户的token号和openid

    /**
     * 获取AccessToken,通常为2个小时,需要将其存储并定时更新
     * 获取openid
     *
     * @return
     */
    @CrossOrigin(origins = {"*", "3600"})  //跨域注解,所有域名都可访问,且cookie的有效期为3600秒
    @GetMapping("/getAccessToken")
    public Map<String, String> getAccesToken(@RequestParam("code") String code) throws IOException {
        Map<String, String> results = new HashMap<>();//存放所有返回消息(Token及其有效时长、openid)

        Map<String, String> params = new HashMap<>();
        params.put("APPID", "wx5cf231d4d4a01697");//小程序id
        params.put("APPSECRET", "3ca5caf950967c1207e722f3ff890821");//小程序密码

        //访问接口,获取Access_Token和有效时长expires_in
        RestTemplate restTemplate = new RestTemplate();// RestTemplate来实现一个get请求,这样就可以轻松获取到access_token。
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);

        String body = responseEntity.getBody();//接收返回的信息
        JSONObject object = JSON.parseObject(body);


        results.put("Access_Token", object.getString("access_token"));
        results.put("expires_in", object.getString("expires_in"));//通常为2个小时,需要将其存储并定时更新


        //访问接口,获取openId
        String openidResult = "";
        try {//请求微信服务器,用code换取openid。HttpUtil是工具类,后面会给出实现,Configure类是小程序配置信息,后面会给出代码
            openidResult = HttpUtil.doGet(
                    "https://api.weixin.qq.com/sns/jscode2session?appid="
                            + params.get("APPID") + "&secret="
                            + params.get("APPSECRET") + "&js_code="
                            + code
                            + "&grant_type=authorization_code", null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ObjectMapper mapper = new ObjectMapper();
        OpenIdJson openIdJson = mapper.readValue(openidResult, OpenIdJson.class);
        results.put("openId", openIdJson.getOpenid());

        LOGININFO =results;
        
        return results;
    }


}

参考文章:
https://cloud.tencent.com/developer/article/1564973

你可能感兴趣的:(小程序)