refactor(utils): 修复密码哈希比较逻辑错误 feat(user): 新增按状态筛选优惠券接口 docs: 添加虚拟发货与任务中心相关文档 fix(wechat): 修正Code2Session上下文传递问题 test: 补充订单折扣与积分转换测试用例 build: 更新配置文件与构建脚本 style: 清理多余的空行与注释
55 lines
1.4 KiB
Go
55 lines
1.4 KiB
Go
package wechat
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"bindbox-game/internal/pkg/httpclient"
|
|
)
|
|
|
|
type Code2SessionResponse struct {
|
|
OpenID string `json:"openid"`
|
|
UnionID string `json:"unionid,omitempty"`
|
|
SessionKey string `json:"session_key"`
|
|
ErrCode int `json:"errcode,omitempty"`
|
|
ErrMsg string `json:"errmsg,omitempty"`
|
|
}
|
|
|
|
func Code2Session(ctx context.Context, config *WechatConfig, code string) (*Code2SessionResponse, error) {
|
|
if config == nil || config.AppID == "" || config.AppSecret == "" {
|
|
return nil, fmt.Errorf("微信配置缺失")
|
|
}
|
|
if code == "" {
|
|
return nil, fmt.Errorf("code 不能为空")
|
|
}
|
|
client := httpclient.GetHttpClient()
|
|
resp, err := client.R().
|
|
SetContext(ctx).
|
|
SetQueryParams(map[string]string{
|
|
"appid": config.AppID,
|
|
"secret": config.AppSecret,
|
|
"js_code": code,
|
|
"grant_type": "authorization_code",
|
|
}).
|
|
Get("https://api.weixin.qq.com/sns/jscode2session")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if resp.StatusCode() != http.StatusOK {
|
|
return nil, fmt.Errorf("HTTP错误: %d", resp.StatusCode())
|
|
}
|
|
var r Code2SessionResponse
|
|
if err := json.Unmarshal(resp.Body(), &r); err != nil {
|
|
return nil, err
|
|
}
|
|
if r.ErrCode != 0 {
|
|
return nil, fmt.Errorf(r.ErrMsg)
|
|
}
|
|
if r.OpenID == "" || r.SessionKey == "" {
|
|
return nil, fmt.Errorf("响应缺少必要字段")
|
|
}
|
|
return &r, nil
|
|
}
|