package cn.com.ty.lift.system.wechat.utils;

import cn.com.ty.lift.system.wechat.constants.WxConstants;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * @author huangyuan
 * @date 2019-12-30
 * @description
 */
public class WxUtil {

    /**
     * @param authCode 用户授权码
     * @return openId
     * @description app端通过用户授权码获取用户openId
     */
    public static String getAppOpenIdByAuthCode(String authCode) {
        return getOpenIdByAuthCode(authCode, WxConstants.AppConfigConstants.OPEN_ID_URL,
                WxConstants.AppConfigConstants.APP_ID,
                WxConstants.AppConfigConstants.APP_SECRET);
    }

    /**
     * @param authCode 用户授权码
     * @return openId
     * @description 小程序端通过用户授权码获取用户openId
     * @date 2020/4/27 10:36 上午
     */
    public static String getAppletOpenIdByAuthCode(String authCode) {
        return getOpenIdByAuthCode(authCode, WxConstants.AppletConfigConstants.OPEN_ID_URL,
                WxConstants.AppletConfigConstants.APP_ID,
                WxConstants.AppletConfigConstants.APP_SECRET);
    }

    /**
     * @param authCode 用户授权码
     * @return openId
     * @description 小程序端扫码获取用户openId
     * @date 2020/4/27 10:36 上午
     */
    public static String getAppletScanOpenIdByAuthCode(String authCode) {
        return getOpenIdByAuthCode(authCode, WxConstants.ScanCodeConfigConstants.OPEN_ID_URL,
                WxConstants.ScanCodeConfigConstants.APP_ID,
                WxConstants.ScanCodeConfigConstants.APP_SECRET);
    }


    /**
     * @param authCode  授权码
     * @param appId     appId
     * @param appSecret appSecret
     * @return openId
     * @description 通过授权码获取微信openId
     * @date 2020/4/30 2:47 下午
     */
    private static String getOpenIdByAuthCode(String authCode, String url, String appId, String appSecret) {
        url = url.replace("APPID", appId)
                .replace("SECRET", appSecret)
                .replace("CODE", authCode);
        JSONObject result = JSONUtil.parseObj(HttpUtil.get(url));
        if (result.containsKey("openid")) {
            return result.getStr("openid");
        }
        return null;
    }

}
