const axios = require("axios");
const config = require("../config");

async function code2session(code) {
  const { appid, secret } = config.wechat;
  const url = "https://api.weixin.qq.com/sns/jscode2session";
  const { data } = await axios.get(url, {
    params: { appid, secret, js_code: code, grant_type: "authorization_code" },
  });

  if (data.errcode) {
    throw new Error(`微信登录失败: ${data.errmsg} (errcode=${data.errcode})`);
  }

  return { openid: data.openid, sessionKey: data.session_key };
}

module.exports = { code2session };
