signature_gen_logic.go 2.2 KB

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