// 操作接口-微信小程序登录
// 秒寻科技
// 周涛
//2024-02-03

package wxminiloginapi

import (
	"encoding/json"
	"ipsomc/core/dao/mysql/mysqlapi"
	"ipsomc/core/wxminilogin/wxminiloginmodel"
	"ipsomc/util"
)

type WxMiniLoginApi struct {
	MySqlApi mysqlapi.MySqlApi
}

// 获取小程序用户的openid
func (obj *WxMiniLoginApi) GetOpenIdByCode(dataModel *wxminiloginmodel.UserMobileLogin) error {
	baseUrl := "https://api.weixin.qq.com/sns/jscode2session"
	headerMap := make(map[string]string)
	headerMap["Content-type"] = "application/json"

	paramMap := make(map[string]string)
	myViper := util.GetViper()
	paramMap["appid"] = myViper.GetString("ms.appid")
	paramMap["secret"] = myViper.GetString("ms.secret")
	paramMap["js_code"] = dataModel.Code
	paramMap["grant_type"] = myViper.GetString("ms.grant_type")

	//发请求获得openid
	byteList, err := util.GetRequest(baseUrl, headerMap, paramMap)
	if err != nil {
		return err
	}

	//将[]byte转成结构体，微信服务器值返回session_key和openid两个参数
	if err := json.Unmarshal(byteList, dataModel); err != nil {
		return err
	}

	return nil
}
