微信小程序授权登录(后台)

参考文章:微信小程序授权登录

测试和正式都有一个appid和secret以供调用微信授权接口,需要前台生成一个code即可,此博客为后台处理接口

// 微信小程序授权登录
@RequestMapping(value = {"wxauth"}, method = {RequestMethod.GET})
@ResponseBody
public JSONObject wxauth(@RequestBody JSONObject param) throws Exception {
    PageData pd = Tools.readProperties("config/wxauth.properties");
    String uri = "https://api.weixin.qq.com/sns/jscode2session?appid="+pd.get("appid")+"&secret="+pd.get("secret")+"&js_code="+param.get("code")+"&grant_type=authorization_code";
    String result = this.doCurl(uri);
    JSONObject json = JSONObject.fromObject(result);
    /*if(null==json.get("errcode")){
        PageData pd = new PageData();
        pd.put("avatar", param.get("avatarUrl"));
        pd.put("province", param.get("province"));
        pd.put("city", param.get("city"));
        pd.put("nickName", param.get("nickName"));
        json.putAll(pd);
    }*/
    return json;
}
/**
 * 读取Properties文件里的全部内容
 * @param fileP  文件路径
 */
public static PageData readProperties(String fileP) {
    PageData pd = new PageData();
    Properties properties = new Properties();
    // 使用ClassLoader加载properties配置文件生成对应的输入流
    InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileP);
    try {
        // 使用properties对象加载输入流
        properties.load(in);
        //获取key对应的value值
        Enumeration enumeration = properties.propertyNames();
        while(enumeration.hasMoreElements()){
            String key = enumeration.nextElement().toString();
            pd.put(key,properties.getProperty(key));
        }
    } catch (IOException e) {
        System.out.println("读取文件内容出错");
    }
    return pd;
}
// java跳转url
private String doCurl(String uri) {
    String result = "";
    try {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Map data = new HashMap();
            data.put("code", "001");
            data.put("name", "测试");

            HttpPost httpPost = new HttpPost(uri + "/test");
            httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
            httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(data),
                    ContentType.create("text/json", "UTF-8")));

            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
            System.out.println(result);
        } finally {
            if (response != null) {
                response.close();
            }
            if (client != null) {
                client.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

Properties文件

微信小程序授权登录(后台)_第1张图片

运行结果:(因为我已经调用过一次,所以我这里失效了)

微信小程序授权登录(后台)_第2张图片

 

你可能感兴趣的:(java,Tools)