package com.jeequan.jeepay.thirdparty.util;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import me.chanjar.weixin.common.error.WxErrorException;

/***
 * 单独写获取 code2Session的接口
 * wxJava每次都会调用： session, 如果两个同时调用可能造成互相占用的情况。
 *
 * @author terrfly
 * @date 2023/9/9 16:42
 */
public class WxLiteCodeUtils {

    public static final String REQ_URL = "https://api.weixin.qq.com/sns/jscode2session";

    // https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
    public static WxMaJscode2SessionResult code2OpenId(String appId, String secret, String jsCode) throws WxErrorException {

        JSONObject params = new JSONObject();
        params.put("appid", appId);
        params.put("secret", secret);
        params.put("js_code", jsCode);
        params.put("grant_type", "authorization_code");


        String res = HttpUtil.get(REQ_URL, params);

        if(res == null){
            throw new WxErrorException("返回数据为空");
        }

        JSONObject resObject = JSONObject.parseObject(res);

        if(resObject.getInteger("errcode") != null && resObject.getInteger("errcode") != 0){
            throw new WxErrorException(resObject.getString("errmsg"));
        }

        WxMaJscode2SessionResult result = new WxMaJscode2SessionResult();
        result.setSessionKey(resObject.getString("session_key"));
        result.setUnionid(resObject.getString("unionid"));
        result.setOpenid(resObject.getString("openid"));
        return result;
    }

    // https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
    public static WxMaJscode2SessionResult code2OpenId(WxMaService wxMaService, String jsCode) throws WxErrorException {
        return code2OpenId(wxMaService.getWxMaConfig().getAppid(), wxMaService.getWxMaConfig().getSecret(), jsCode);
    }

}
