package com.fs.app.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class WxUtil {
    private static final Logger logger = LoggerFactory.getLogger(WxUtil.class);
    private static final String getAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
    private static final String refreshTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token";
    private static final String getUserInfo = "https://api.weixin.qq.com/sns/userinfo";


    /**
     * 获取微信AccessToken
     * @param code 用户code
     * @return
     */
    public static Map<?, ?> getAccessToken(String code, String appid, String secret) {
        StringBuffer url = new StringBuffer();
        url.append(getAccessTokenUrl)
                .append("?appid=")
                .append(appid)
                .append("&secret=")
                .append(secret)
                .append("&code=")
                .append(code)
                .append("&grant_type=authorization_code");
        String rs = HttpUtil.get(url.toString());
        Map map = JSONObject.parseObject(rs, Map.class);
        if (null == map.get("errcode")) {
            return map;
        } else {
            logger.info("获取access_token出错，错误信息：" + map);
            throw new RuntimeException("获取access_token出错");
        }
    }

    /**
     * 刷新AccessToken
     * @param refreshToken
     * @return
     */
    public static Map refreshToken(String refreshToken,String appid) {
        StringBuffer url = new StringBuffer();
        url.append(refreshTokenUrl)
                .append("?appid=")
                .append(appid)
                .append("&grant_type=refresh_token&refresh_token=")
                .append(refreshToken);
        String rs = HttpUtil.get(url.toString());
        Map map = JSONObject.parseObject(rs, Map.class);
        if (null == map.get("errcode")) {
            return map;
        } else {
            throw new RuntimeException("刷新access_token出错");
        }
    }

    /**
     * 获取用户信息
     * @param accessToken
     * @param openid
     * @return
     */
    public static Map getUserInfo(String accessToken, String openid) {
        StringBuffer url = new StringBuffer();
        url.append(getUserInfo)
                .append("?access_token=")
                .append(accessToken)
                .append("&openid=")
                .append(openid)
                .append("&lang=zh_CN");
        String rs = HttpUtil.get(url.toString());
        Map map = JSONObject.parseObject(rs, Map.class);
        return map;
    }
}
