signature_gen_logic.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package xiaoice
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/zeromicro/go-zero/core/errorx"
  7. "io"
  8. "net/http"
  9. "net/url"
  10. "wechat-api/internal/svc"
  11. "wechat-api/internal/types"
  12. "github.com/zeromicro/go-zero/core/logx"
  13. )
  14. type SignatureGenLogic struct {
  15. logx.Logger
  16. ctx context.Context
  17. svcCtx *svc.ServiceContext
  18. }
  19. func NewSignatureGenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SignatureGenLogic {
  20. return &SignatureGenLogic{
  21. Logger: logx.WithContext(ctx),
  22. ctx: ctx,
  23. svcCtx: svcCtx}
  24. }
  25. func (l *SignatureGenLogic) SignatureGen() (resp *types.SignatureResp, err error) {
  26. // 构建请求URL
  27. key := l.svcCtx.Config.Xiaoice.SubscriptionKey
  28. baseURL, err := url.Parse("https://interactive-virtualhuman.xiaoice.com/openapi/signature/gen")
  29. if err != nil {
  30. return nil, err
  31. }
  32. // 在这里设置请求参数
  33. //params := url.Values{}
  34. // 如果需要设置 token 有效期,请取消下面注释并设置时间(以毫秒为单位)
  35. //params.Add("effectiveDurationMilliseconds", strconv.Itoa(24*60*60*1000))
  36. //baseURL.RawQuery = params.Encode()
  37. // 创建 HTTP 请求
  38. req, err := http.NewRequest("GET", baseURL.String(), nil)
  39. if err != nil {
  40. return nil, err
  41. }
  42. // 添加必要的Header信息
  43. req.Header.Add("subscription-key", key)
  44. // 创建HTTP客户端并执行请求
  45. client := &http.Client{}
  46. response, err := client.Do(req)
  47. if err != nil {
  48. return nil, err
  49. }
  50. defer func(Body io.ReadCloser) {
  51. err := Body.Close()
  52. if err != nil {
  53. l.Error("获取小冰 AuthToken 失败: %v", err)
  54. }
  55. }(response.Body)
  56. // 读取和输出响应
  57. body, err := io.ReadAll(response.Body)
  58. if err != nil {
  59. return nil, err
  60. }
  61. // 检查响应状态
  62. if response.StatusCode != http.StatusOK {
  63. //log.Fatalf("请求失败,状态码:%d,响应: %s", response.StatusCode, string(body))
  64. return nil, errorx.NewDefaultError(fmt.Sprintf("获取小冰 AuthToken 失败:%d,响应: %s", response.StatusCode, string(body)))
  65. }
  66. // 解析 JSON 响应
  67. var responseMap types.XiaoiceSignatureResp
  68. if err := json.Unmarshal(body, &responseMap); err != nil {
  69. return nil, err
  70. }
  71. fmt.Printf("响应: %s\n", string(body))
  72. return &types.SignatureResp{Data: &responseMap.Data}, nil
  73. }