签发一次性登录票据
POST
/api/v1/open/viewers/login-tickets为已有观众生成直接进入活动观看页的登录链接。
使用场景
你的服务端先创建或更新观众,再为其签发票据。把返回的 loginUrl 交给该用户,浏览器打开后,观看页用票据交换登录会话。
不要让最终用户持有 API Key 或 Secret;用户只需要自己的登录链接。
请求参数
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
uid | integer | 是 | 先调用创建或更新观众取得本商户 UID,10000–9999999。 |
ticketCode | string | 是 | 活动公开码,从商家控制台观看链接 /w/{ticketCode} 获取;不是活动 ID。 |
返回值
| 字段 | 类型 | 始终返回 | 说明 |
|---|---|---|---|
requestId | string | 是 | 请求追踪编号,排查问题时提供此值。 |
data | object | 是 | 业务结果。 |
data.loginTicket | string | 是 | 一次性登录票据,只交给目标观众;不要记录日志或共享。 |
data.loginUrl | string | 是 | 带 #login_ticket=… 的完整观看 URL,可直接跳转。 |
data.expiresAt | string | 是 | 失效时间,UTC RFC3339,例如 2026-10-12T08:01:00Z。 |
json
{
"requestId": "req-example-002",
"data": {
"loginTicket": "example-one-time-ticket",
"loginUrl": "https://watch.example.com/w/demo-live#login_ticket=example-one-time-ticket",
"expiresAt": "2026-10-12T08:01:00Z"
}
}域名、票据和时间均为示例。直接使用 API 返回的完整 URL,可兼容商户自定义观看域名。
使用规则
ticketCode是活动观看入口码,来自控制台观看链接/w/{ticketCode}。UID 与活动都必须属于 API Key 对应的商户;草稿、暂停(SUSPENDED)及已隐藏活动不可用。- 票据只能交换一次。有效期由服务端配置决定,配置示例为 60 秒,以
expiresAt为准;建议在用户即将跳转时签发。 - 同一商户的同一观众重新签发票据,会使其之前的未使用票据失效,即使两次签发指向不同活动。避免提前批量签发或并发签发。
- 票据位于 URL 的
#login_ticket=…片段中,请完整传递,不要改写成查询参数。票据和完整链接应按临时登录凭证处理,不写入公开日志。 - 票据用于登录身份。活动的状态与观看规则仍以观看页实际判断为准。
相关错误
| HTTP | error.code | 处理方式 |
|---|---|---|
| 400 | REQUEST_INVALID | 检查 UID 范围与活动入口码 |
| 404 | VIEWER_NOT_FOUND | 确认 UID 来自当前商户 |
| 404 | WEBINAR_NOT_FOUND | 检查入口码、所属商户及活动是否已发布 |
| 503 | PUBLIC_METADATA_UNAVAILABLE | 活动入口信息暂不可用,稍后重试 |
| 503 | VIEWER_DOMAIN_UNAVAILABLE | 观看域名或其映射暂不可用,联系部署方 |
通用错误见错误码与排查。发送失败时先核对结果,避免重复签发导致前一个链接失效。
请求示例
将示例 UID 和 ticketCode 改为当前商户的真实值。
运行前设置 OPEN_API_BASE_URL、OPEN_API_KEY 和 OPEN_API_SECRET 环境变量。示例只发一次请求,不自动重试。
cURL
# 先设置 OPEN_API_BASE_URL、OPEN_API_KEY、OPEN_API_SECRET;请使用当前环境的凭证。
set -eu
: "${OPEN_API_BASE_URL:?请设置 HTTPS API Origin}"
: "${OPEN_API_KEY:?请设置 API Key}"
: "${OPEN_API_SECRET:?请设置 Secret}"
export OPEN_API_PATH='/api/v1/open/viewers/login-tickets'
export OPEN_API_BODY='{"uid":10000,"ticketCode":"demo-live"}'
export OPEN_API_TIMESTAMP="$(date +%s)"
export OPEN_API_NONCE="$(python3 -c 'import secrets; print(secrets.token_hex(16))')"
SIGNATURE="$(python3 - <<'PY'
import hashlib, hmac, os
body = os.environ['OPEN_API_BODY'].encode('utf-8')
canonical = '\n'.join([os.environ['OPEN_API_KEY'], 'POST', os.environ['OPEN_API_PATH'], os.environ['OPEN_API_TIMESTAMP'], os.environ['OPEN_API_NONCE'], hashlib.sha256(body).hexdigest()])
print(hmac.new(os.environ['OPEN_API_SECRET'].encode('utf-8'), canonical.encode('utf-8'), hashlib.sha256).hexdigest())
PY
)"
# 不使用 -v 或调试日志;响应可能含观众资料或一次性登录票据。
curl --silent --show-error --max-time 15 \
--request POST "${OPEN_API_BASE_URL%/}${OPEN_API_PATH}" \
--header 'Content-Type: application/json' \
--header "X-API-Key: ${OPEN_API_KEY}" \
--header "X-Timestamp: ${OPEN_API_TIMESTAMP}" \
--header "X-Nonce: ${OPEN_API_NONCE}" \
--header "X-Signature: ${SIGNATURE}" \
--data-binary "${OPEN_API_BODY}"
Java
// Java 17+;只使用标准库。
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
class OpenApiExample {
private static String requiredEnv(String name) {
String value = System.getenv(name);
if (value == null || value.isBlank()) throw new IllegalArgumentException("请设置环境变量 " + name);
return value;
}
public static void main(String[] args) throws Exception {
String baseURL = requiredEnv("OPEN_API_BASE_URL").replaceFirst("/+$", "");
String apiKey = requiredEnv("OPEN_API_KEY");
String secret = requiredEnv("OPEN_API_SECRET");
String path = "/api/v1/open/viewers/login-tickets";
String rawBody = "{\"uid\":10000,\"ticketCode\":\"demo-live\"}";
byte[] bodyBytes = rawBody.getBytes(StandardCharsets.UTF_8);
String timestamp = Long.toString(System.currentTimeMillis() / 1000);
byte[] nonceBytes = new byte[16];
new SecureRandom().nextBytes(nonceBytes);
String nonce = HexFormat.of().formatHex(nonceBytes);
String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bodyBytes));
String canonical = String.join("\n", apiKey, "POST", path, timestamp, nonce, bodyHash);
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
String signature = HexFormat.of().formatHex(mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8)));
HttpRequest request = HttpRequest.newBuilder(URI.create(baseURL + path))
.timeout(Duration.ofSeconds(15))
.header("Content-Type", "application/json")
.header("X-API-Key", apiKey)
.header("X-Timestamp", timestamp)
.header("X-Nonce", nonce)
.header("X-Signature", signature)
.POST(HttpRequest.BodyPublishers.ofByteArray(bodyBytes))
.build();
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(15))
.followRedirects(HttpClient.Redirect.NEVER)
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
// 仅在本地对接时查看完整响应;正式业务请用项目的 JSON 库解析,禁止记录完整观众资料或登录票据。
System.out.printf("status=%d%n%s%n", response.statusCode(), response.body());
}
}
PHP
<?php
// PHP 8.1+;需要 cURL 扩展,不依赖第三方包。
function required_env(string $name): string {
$value = getenv($name);
if ($value === false || $value === '') {
throw new RuntimeException('请设置环境变量 ' . $name);
}
return $value;
}
$baseURL = rtrim(required_env('OPEN_API_BASE_URL'), '/');
$apiKey = required_env('OPEN_API_KEY');
$secret = required_env('OPEN_API_SECRET');
$path = '/api/v1/open/viewers/login-tickets';
$rawBody = '{"uid":10000,"ticketCode":"demo-live"}';
$timestamp = (string) time();
$nonce = bin2hex(random_bytes(16));
$bodyHash = hash('sha256', $rawBody);
$canonical = implode("\n", [$apiKey, 'POST', $path, $timestamp, $nonce, $bodyHash]);
$signature = hash_hmac('sha256', $canonical, $secret);
$curl = curl_init($baseURL . $path);
if ($curl === false) {
throw new RuntimeException('无法初始化 cURL');
}
curl_setopt_array($curl, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $rawBody,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'X-API-Key: ' . $apiKey,
'X-Timestamp: ' . $timestamp,
'X-Nonce: ' . $nonce,
'X-Signature: ' . $signature,
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT => 15,
CURLOPT_TIMEOUT => 15,
]);
$responseBody = curl_exec($curl);
if ($responseBody === false) {
$message = curl_error($curl);
curl_close($curl);
throw new RuntimeException('请求失败:' . $message);
}
$status = (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
curl_close($curl);
$result = json_decode($responseBody, true, 512, JSON_THROW_ON_ERROR);
// result['data'] 交给业务处理;不要记录完整响应和票据。
printf("status=%d requestId=%s errorCode=%s\n", $status, $result['requestId'] ?? '', $result['error']['code'] ?? '');
Node.js
// Node.js 22+;使用内置 fetch 和 crypto,无额外依赖。
import { createHash, createHmac, randomBytes } from 'node:crypto'
const { OPEN_API_BASE_URL: baseURL, OPEN_API_KEY: apiKey, OPEN_API_SECRET: secret } = process.env
if (!baseURL || !apiKey || !secret) throw new Error('请设置环境变量')
const path = '/api/v1/open/viewers/login-tickets'
const rawBody = "{\"uid\":10000,\"ticketCode\":\"demo-live\"}"
const timestamp = String(Math.floor(Date.now() / 1000))
const nonce = randomBytes(16).toString('hex')
const bodyHash = createHash('sha256').update(rawBody, 'utf8').digest('hex')
const canonical = [apiKey, 'POST', path, timestamp, nonce, bodyHash].join('\n')
const signature = createHmac('sha256', secret).update(canonical, 'utf8').digest('hex')
const response = await fetch(baseURL.replace(/\/$/, '') + path, {
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(15000),
headers: { 'Content-Type': 'application/json', 'X-API-Key': apiKey, 'X-Timestamp': timestamp, 'X-Nonce': nonce, 'X-Signature': signature },
body: rawBody,
})
const result = await response.json()
// result.data 交给业务处理;不要将凭证、登录票据或完整观众资料写入日志。
console.log({ status: response.status, requestId: result.requestId, errorCode: result.error?.code })
Python
# Python 3.9+;只使用标准库。
import hashlib, hmac, json, os, secrets, time
from urllib.request import Request, build_opener, HTTPRedirectHandler
from urllib.error import HTTPError
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
base_url = os.environ['OPEN_API_BASE_URL'].rstrip('/')
api_key = os.environ['OPEN_API_KEY']
secret = os.environ['OPEN_API_SECRET']
path = '/api/v1/open/viewers/login-tickets'
raw_body = "{\"uid\":10000,\"ticketCode\":\"demo-live\"}".encode('utf-8')
timestamp, nonce = str(int(time.time())), secrets.token_hex(16)
canonical = '\n'.join([api_key, 'POST', path, timestamp, nonce, hashlib.sha256(raw_body).hexdigest()])
signature = hmac.new(secret.encode('utf-8'), canonical.encode('utf-8'), hashlib.sha256).hexdigest()
request = Request(base_url + path, data=raw_body, method='POST', headers={
'Content-Type': 'application/json', 'X-API-Key': api_key,
'X-Timestamp': timestamp, 'X-Nonce': nonce, 'X-Signature': signature,
})
try:
response = build_opener(NoRedirect).open(request, timeout=15)
except HTTPError as error:
response = error
result = json.load(response)
# 将 result['data'] 交给业务处理;不要记录完整响应和票据。
print({'status': response.code, 'requestId': result.get('requestId'), 'errorCode': result.get('error', {}).get('code')})
Go
// Go 1.22+;只使用标准库。
package main
import (
"bytes"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"strings"
"time"
)
func main() {
baseURL, apiKey, secret := os.Getenv("OPEN_API_BASE_URL"), os.Getenv("OPEN_API_KEY"), os.Getenv("OPEN_API_SECRET")
if baseURL == "" || apiKey == "" || secret == "" { panic("请设置环境变量") }
path := "/api/v1/open/viewers/login-tickets"
rawBody := []byte("{\"uid\":10000,\"ticketCode\":\"demo-live\"}")
nonceBytes := make([]byte, 16)
if _, err := rand.Read(nonceBytes); err != nil { panic("随机数生成失败") }
timestamp, nonce := strconv.FormatInt(time.Now().Unix(), 10), hex.EncodeToString(nonceBytes)
digest := sha256.Sum256(rawBody)
canonical := strings.Join([]string{apiKey, "POST", path, timestamp, nonce, hex.EncodeToString(digest[:])}, "\n")
mac := hmac.New(sha256.New, []byte(secret)); mac.Write([]byte(canonical))
req, err := http.NewRequest("POST", strings.TrimRight(baseURL, "/") + path, bytes.NewReader(rawBody))
if err != nil { panic("请求构建失败") }
for name, value := range map[string]string{"Content-Type":"application/json", "X-API-Key":apiKey, "X-Timestamp":timestamp, "X-Nonce":nonce, "X-Signature":hex.EncodeToString(mac.Sum(nil))} { req.Header.Set(name,value) }
client := &http.Client{Timeout:15*time.Second, CheckRedirect:func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }}
resp, err := client.Do(req)
if err != nil { panic("网络请求失败,请检查连接") }
defer resp.Body.Close()
var result map[string]any
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { panic("响应不是 JSON") }
// result["data"] 交给业务处理;只记录状态和请求编号。
fmt.Printf("status=%d requestId=%v\n", resp.StatusCode, result["requestId"])
}