package com.heyu.api.data.utils;

import com.alibaba.fastjson.JSON;
import com.heyu.api.data.dto.WeiChatLoginDTO;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;

@Slf4j
public class WechatUtils {

    /**
     * 微信 auth.code2Session 接口
     */
    public final static String WECHAT_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    public final static String WECHAT_APPID = "wx75fa59c097bd3dfd";
    public final static String WECHAT_SECRET = "1837c382de696013a2dfc64591e6b854";

    public static void main(String[] args) {
        // 获取 openid
        WeiChatLoginDTO weiChatLoginDTO = getOpenId("0b1tMGll2jJdBg4sfwml2pnGk32tMGlg");
        System.out.println(weiChatLoginDTO.getOpenid());
        System.out.println("o6t1512tT-JuBeT6rIu6RhFGf3BQ".length());
        System.out.println("FMOMCp63WoRFUJtL4tvjcQ==".length());

    }

    /**
     * 通过微信登录code获取openId
     *
     * @param code 微信登录code
     * @return openId
     */
    // ============json============{"session_key":"FMOMCp63WoRFUJtL4tvjcQ==","openid":"o6t1512tT-JuBeT6rIu6RhFGf3BQ"}
    public static WeiChatLoginDTO getOpenId(String code) {
        try {
            // 添加参数
            HashMap<String, String> map = new HashMap<>();
            map.put("appid", WECHAT_APPID);
            map.put("secret", WECHAT_SECRET);
            map.put("js_code", code);
            map.put("grant_type", "authorization_code");
            // 使用封装好的HttpClientUtil工具类发送请求
            String json = HttpUtils.doGet(WECHAT_LOGIN_URL, map);
            System.out.println("============json============" + json);
            // 将JSON字符串转换为JSONObject对象
            WeiChatLoginDTO weiChatLoginDTO = JSON.parseObject(json, WeiChatLoginDTO.class);
            // 从JSONObject中获取openid并返回
            return weiChatLoginDTO;
        } catch (Exception e) {
            log.error("getOpenId error", e);
        }
        return null;
    }

}
