Authorization
If developers do not need the Polyv SaaS viewing condition verification feature, they can generate an audience authorization token (hereinafter referred to as the Authorization Token) via the Polyv API. Once the authorization token is verified and passed in, the viewing condition restrictions can be bypassed to enter the live streaming page. For detailed usage, please refer to the following documentation:
1. Process Flow
1.1 Step 1: Create a Viewing Core Instance
Please refer to Viewing Page SDK - Installation and Initialization
1.2 Step 2: Obtain the Authorization Token
Obtain the audience authorization token via the Polyv API. See the API documentation: Obtain the Viewing Page SDK Authorization Token.
Since this API involves parameter signing with
appSecret, it is recommended that this step be performed on the server side.
1.3 Step 3: Pass in the Authorization Token
After obtaining the authorization token from Step 2, pass it in using the setXAuthToken method of the core instance.
1.4 Step 4: Install the Viewing Core Instance
After passing in the token from Step 3, proceed with the normal process to install the core instance. Note that the authorization token flow is only required before the first installation; it is not needed for subsequent installations.
2. Example Code
Below is an example code snippet for the JavaScript process:
import { send } from '@just4/ajax/ajax';
import md5 from 'md5';
import { createWatchCore } from '@polyv/live-watch-sdk';
/**
* 生成签名
* @param {Object} data 请求参数
* @param {String} secret 签名密钥
* @returns 签名串
*/
function getSign(data, secret) {
let text = '';
const keys = Object.keys(data).sort();
for (const key of keys) {
text += `${key}${data[key]}`;
}
const sign = md5(secret + text + secret);
return sign.toUpperCase();
}
/**
* 获取授权令牌(注:如果在观看页开源UI项目用到此接口,建议把观众信息封装成全局统一,分别传入以下接口和观看页SDK核心实例方法createWatchCore)
* @param {string} channelId
*/
async function getWatchAuthToken({ channelId }) {
// 请求数据
const reqData = {
appId: '应用 id,从管理后台获取', // 必传
timestamp: Date.now(),// 必传
channelId, // '频道ID',// 必传
viewerId: '观众 id',// 建议必传,否则将随机生成
nickname: '观众昵称',// 建议必传,否则将以XX地区观众展示
avatar: '观众头像',// 不传的话,会采用默认头像
actor:'观众头衔', // 不传的话,默认可自动读取频道管理后台的配置
};
// 应用密钥,从管理后台获取,建议获取授权令牌流程在服务端中进行,避免将应用密钥直接暴露在 js 中
const appSecret = 'xxxxx';
// 生成签名
const sign = getSign(reqData, appSecret);
reqData.sign = sign;
// 通过XHR获取授权令牌(注意:开发者如果使用非seed请求方式,post传递的数据格式需要是Form-data)
const response = await send('//api.polyv.net/live/v3/channel/watch/get-watch-api-token', {
method: 'post',
data: reqData,
});
const result = response.data;
return result.data.token;
}
// 示例方法
async function example() {
const channelId = '频道号';
// 步骤1:创建观看核心实例
const watchCore = createWatchCore({ channelId });
// 步骤2:获取授权令牌
const watchAuthToken = await getWatchAuthToken({ channelId });
// 步骤3:传入授权令牌
watchCore.setXAuthToken(watchAuthToken);
// 步骤4:安装观看核心实例
await watchCore.setup();
}
