finclip-app-manager/infrastructure/client/httpcall/wechat.go

63 lines
2.1 KiB
Go
Raw Normal View History

2023-10-31 14:07:26 +08:00
package httpcall
import (
"context"
"encoding/json"
"errors"
"finclip-app-manager/domain/entity/proto/apiproto"
"fmt"
"net/http"
)
func (c *Client) GetWechatQrcode(ctx context.Context, req apiproto.UpdateWechatInfoReq, token string) ([]byte, error) {
url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=%s", token)
body := map[string]interface{}{
"path": req.WechatPath,
"width": 430,
}
rsp, err := c.Request(ctx).SetBody(body).Post(url)
if err != nil {
log.Errorf("getWechatQrcode err:%+v,status code:%+v", err, rsp)
return nil, err
}
if rsp.StatusCode() != http.StatusOK {
log.Errorf("getWechatQrcode status code no 200 :%+v,boyd:%+v", rsp.StatusCode(), rsp.String())
return nil, errors.New("getWechatQrcode status code no ok")
}
if rsp.Header().Get("Content-Type") != "image/jpeg" {
log.Errorf("getWechatQrcode Content-Type not jpeg :%+v, body: %s", rsp.Header().Get("Content-Type"), string(rsp.Body()))
return nil, errors.New("getWechatQrcode Content-Type no ok")
}
log.Infof("getWechatQrcode rsp:%+v", rsp.Header())
return rsp.Body(), nil
}
type WechatAccessToeknRsp struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
}
func (c *Client) GetAccessToken(ctx context.Context, req apiproto.UpdateWechatInfoReq) (string, error) {
url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", req.WechatAppId, req.WechatAppSecret)
rsp, err := c.Request(ctx).Get(url)
if err != nil {
log.Errorf("getAccessToken client req err:%s", err.Error())
return "", err
}
if rsp.StatusCode() != 200 {
log.Errorf("getAccessToken rsp code err:%s", rsp.String())
return "", errors.New("getAccessToken rsp code no 200")
}
resp := WechatAccessToeknRsp{}
err = json.Unmarshal(rsp.Body(), &resp)
if err != nil {
log.Errorf("Failed to unmarshal WechatAccessToeknRsp: %v\n", err)
return "", err
}
log.Infof("getAccessToken resp:%+v", resp)
if resp.AccessToken == "" {
return "", fmt.Errorf("getAccessToken fail check appId")
}
return resp.AccessToken, nil
}