0. 注册账号,新人会免费用7天

polyv官网地址icon-default.png?t=M0H8http://www.polyv.net/vod/

一. 根据图片步骤,创建视频分类并上传测试视频

a. 

  b.

 c.

 d. 

 二. 参数介绍

官方文档icon-default.png?t=M0H8https://dev.polyv.net/2019/videoproduct/v-api/v-api-play/create-playsafe-token/

1. 默认生成的参数,我们客户端视频加密播放需要的

 

2. 请求token携带的参数

3. 视频的vid 我们需要传送到后端必填参数之一

 

4. 响应数据(我们只要token即可)

{
    "code": 200,
    "status": "success",
    "message": "",
    "data": {
        "token": "973d7731803940a1b14fdc93941f493c",
        "userId": "e6b23c6f51",
        "videoId": "e6b23c6f51c4b1cb9f0302a92ed42440_e",
        "viewerIp": "127.0.0.1",
        "viewerId": "abcd1234",
        "viewerName": null,
        "extraParams": null,
        "ttl": 600000,
        "createdTime": 1552446282044,
        "expiredTime": 1552446882044,
        "iswxa": 0,
        "disposable": false
    }
}

三. web视频加密播放

1. 后端

a. 创建一个utils.py

# -*- coding:utf-8 -*-
import time
import requests
# pip install requests
import hashlib


class PolyvPlayer(object):
    def __init__(self, userId, secretkey, tokenUrl):
        """初始化,提供用户id和秘钥"""
        self.userId = userId
        self.secretKey = secretkey
        self.tokenUrl = tokenUrl

    def tomd5(self, value):
        """取md5值"""
        return hashlib.md5(value.encode('utf-8')).hexdigest()

    # 获取视频数据的token
    def get_video_token(self, videoId, viewerIp, viewerId=None, viewerName='', extraParams='HTML5'):
        """
        :param videoId: 视频id
        :param viewerId: 看视频用户id
        :param viewerIp: 看视频用户ip
        :param viewerName: 看视频用户昵称
        :param extraParams: 扩展参数
        :param sign: 加密的sign
        :return: 返回点播的视频的token
        """
        ts = int(time.time() * 1000)  # 时间戳
        plain = {
            "userId": self.userId,
            'videoId': videoId,
            'ts': ts,
            'viewerId': viewerId,
            'viewerIp': viewerIp,
            'viewerName': viewerName,
            'extraParams': extraParams
        }

        # 按照ASCKII升序 key + value + key + value... + value 拼接
        plain_sorted = {}
        key_temp = sorted(plain)
        for key in key_temp:
            plain_sorted[key] = plain[key]
        print(plain_sorted)

        plain_string = ''
        for k, v in plain_sorted.items():
            plain_string += str(k) + str(v)
        print(plain_string)

        # 首尾拼接上秘钥
        sign_data = self.secretKey + plain_string + self.secretKey

        # 取sign_data的md5的大写
        sign = self.tomd5(sign_data).upper()
        # 新的带有sign的字典
        plain.update({'sign': sign})
        # python 提供的发送http请求的模块
        result = requests.post(
            url=self.tokenUrl,
            headers={"Content-type": "application/x-www-form-urlencoded"},
            data=plain
        ).json()
        token = {} if isinstance(result, str) else result.get("data", {})
        return token

b. url.py

    path('play/video/', views.PlayVideoView.as_view()),

c. settings的配置(配上自己的参数即可)

# 保利威视频加密服务
POLYV_CONFIG = {
    "userId": "xxx",  
    "secretkey": "xxx",
    "tokenUrl": "https://hls.videocc.net/service/v1/token",
}

d. view(直接用即可,封装好了)

from rest_framework.views import APIView
from django.conf import settings
from lyapi.libs.paly.paly_token import PolyvPlayer
from rest_framework.response import Response
class PlayVideoView(APIView):
    permission_classes = [IsAuthenticated, ]

    def get(self, request):
        userId = settings.POLYV_CONFIG.get('userId')
        secretkey = settings.POLYV_CONFIG.get('secretkey')
        tokenUrl = settings.POLYV_CONFIG.get('tokenUrl')
        polyv_player_obj = PolyvPlayer(userId=userId, secretkey=secretkey, tokenUrl=tokenUrl)
        videoId = request.GET.get('vid')  # '8ef6c2d3be1402950288a4d3798644d3_8'
        print(videoId)
        viewerIp = request.META.get('REMOTE_ADDR')
        viewerId = request.user.id
        viewerName = request.user.username
        token_data = polyv_player_obj.get_video_token(videoId, viewerIp, viewerId, viewerName)
        token = token_data.get('token')
        # print(token)
        return Response({'token_data': token})

2. 前端

a. 在index.html中导入js

 <!-- 1 -->
  <script src="//player.polyv.net/script/player.js"></script>

b. 创建一个PlayVideo.vue

<template>
  <!--   2 -->
  <div class="player">
    <div id="player"></div>
  </div>

</template>

<script>
export default {
  name: "PlayVideo",
  data() {
    return {}
  },
  methods: {},
  // created 初始化,放置的是ajax等操作/获取数据的代码,不涉及操作页面
  // mounted 初始化,放置的是关于操作页面的初始化js代码
  mounted() {
    // 1. 到数据库中查询用户购买的课程,是否有当前章节
    // 2. 到数据库中查询当前用户购买的课程是否在有效期内
    // 3. 播放页面显示课程章节和课时的播放列表
    // 4. 通过vid播放不同的课时视频
    // 以上4个功能自行完成
    let vid = this.$route.params.vid; // this.$route.params.vid; 路由参数传递过来  "8ef6c2d3be1402950288a4d3798644d3_8"
    let self = this;
    var player = polyvPlayer({
      wrap: '#player',
      width: document.documentElement.clientWidth - 260, // 页面宽度
      height: document.documentElement.clientHeight, // 页面高度
      forceH5: true,
      vid: vid,
      // 视频加密播放的配置
      playsafe: function (vid, next) { // 向后端发送请求获取加密的token
        // 配置获取自己token的路径
        self.$axios.get(`${self.$settings.host}/order/play/video/`, {
          params: {
            vid: vid,
          },
        })
          .then(function (response) {
            // 获取播放视频的token令牌
            next(response.data.token_data);
          })
      }
    });
  },
  computed: {}
}
</script>

<style scoped>

</style>

c. index.js中配置路由

{
      path: '/play/video/:vid/',  // 通过$route.params.vid获取参数
      name: 'PlayVideo',
      component: PlayVideo
    },

d. 生成一个播放按钮

<button class="try">
     <router-link :to="'/play/video/' + '自己的vid' + '/' ">立即试学</router-link>
</button>

Logo

前往低代码交流专区

更多推荐