| 373 | } |
| 374 | |
| 375 | func genCreemLink(ctx context.Context, referenceId string, product *CreemProduct, email string, username string) (string, error) { |
| 376 | if setting.CreemApiKey == "" { |
| 377 | return "", fmt.Errorf("未配置Creem API密钥") |
| 378 | } |
| 379 | |
| 380 | // 根据测试模式选择 API 端点 |
| 381 | apiUrl := "https://api.creem.io/v1/checkouts" |
| 382 | if setting.CreemTestMode { |
| 383 | apiUrl = "https://test-api.creem.io/v1/checkouts" |
| 384 | logger.LogInfo(ctx, fmt.Sprintf("Creem 使用测试环境 api_url=%s", apiUrl)) |
| 385 | } |
| 386 | |
| 387 | // 构建请求数据,确保包含用户邮箱 |
| 388 | requestData := CreemCheckoutRequest{ |
| 389 | ProductId: product.ProductId, |
| 390 | RequestId: referenceId, // 这个作为订单ID传递给Creem |
| 391 | Customer: struct { |
| 392 | Email string `json:"email"` |
| 393 | }{ |
| 394 | Email: email, // 用户邮箱会在支付页面预填充 |
| 395 | }, |
| 396 | Metadata: map[string]string{ |
| 397 | "username": username, |
| 398 | "reference_id": referenceId, |
| 399 | "product_name": product.Name, |
| 400 | "quota": fmt.Sprintf("%d", product.Quota), |
| 401 | }, |
| 402 | } |
| 403 | |
| 404 | // 序列化请求数据 |
| 405 | jsonData, err := json.Marshal(requestData) |
| 406 | if err != nil { |
| 407 | return "", fmt.Errorf("序列化请求数据失败: %v", err) |
| 408 | } |
| 409 | |
| 410 | // 创建 HTTP 请求 |
| 411 | req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(jsonData)) |
| 412 | if err != nil { |
| 413 | return "", fmt.Errorf("创建HTTP请求失败: %v", err) |
| 414 | } |
| 415 | |
| 416 | // 设置请求头 |
| 417 | req.Header.Set("Content-Type", "application/json") |
| 418 | req.Header.Set("x-api-key", setting.CreemApiKey) |
| 419 | |
| 420 | logger.LogInfo(ctx, fmt.Sprintf("Creem 支付请求已发送 api_url=%s product_id=%s email=%q trade_no=%s", apiUrl, product.ProductId, email, referenceId)) |
| 421 | |
| 422 | // 发送请求 |
| 423 | client := &http.Client{ |
| 424 | Timeout: 30 * time.Second, |
| 425 | } |
| 426 | resp, err := client.Do(req) |
| 427 | if err != nil { |
| 428 | return "", fmt.Errorf("发送HTTP请求失败: %v", err) |
| 429 | } |
| 430 | defer resp.Body.Close() |
| 431 | |
| 432 | // 读取响应 |