Polyv Help Center

Help Center

Authorization

Updated: 2024-10-11 15:26:25

If developers do not need Polyv SaaS's viewing condition verification, 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, the viewing condition restrictions can be bypassed to enter the live streaming page. For detailed usage, 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 Mini Program 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 the Authorization Token

After obtaining the authorization token in Step 2, pass it using the setXAuthToken method of the core instance.

1.4 Step 4: Install the Viewing Core Instance

After passing the token in Step 3, proceed with the normal installation process for 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 of the process flow in JavaScript:

import { send } from '@just4/ajax/ajax';
import md5 from 'md5';
import { createWatchCore } from '@polyv/live-watch-miniprogram-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();
}

/**
 * 获取授权令牌
 * @param {string} channelId
 */
async function getWatchAuthToken({ channelId }) {
  // 请求数据
  const reqData = {
    appId: '应用 id,从管理后台获取',
    timestamp: Date.now(),
    channelId, // '频道ID',
    viewerId: '观众 id',
    nickname: '观众昵称',
    avatar: '观众头像',
  };
  // 应用密钥,从管理后台获取,建议获取授权令牌流程在服务端中进行,避免将应用密钥直接暴露在 js 中
  const appSecret = 'xxxxx';
  // 生成签名
  const sign = getSign(reqData, appSecret);
  reqData.sign = sign;

  // 通过 ajax 获取授权令牌
  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();
}
联系客服,在线咨询