Pay to watch videoΒΆ

Hint

You can see this example in action on the online editor js.do or the hosted example page.

This example shows how to implement a paywall plugin for an HTML/JavaScript video player. We use the open source VideoJS player for this example. As additional imports we need

1
2
3
<link rel="stylesheet" href="https://vjs.zencdn.net/5.2.1/video-js.css">
<!-- and -->
<script src="https://vjs.zencdn.net/5.2.1/video.js"></script>

as a prerequisite. On the page we add

1
2
3
4
5
6
<video id="millipayWallVideo" class="video-js embed-responsive-item"
 controls preload="auto" poster="https://vhs.millipay.ch/oceans.png" data-setup='{}'>
  <source src="https://vhs.millipay.ch/oceans.mp4" type='video/mp4'>
  <source src="https://vhs.millipay.ch/oceans.webm" type='video/webm'>
  <source src="https://vhs.millipay.ch/oceans.ogv" type='video/ogg'>
</video>

to place the HTML5 video on the page. The class video-js is auto-detected by the VideoJS import and supplemented with the VideoJS controls. Now we can write the paywall plugin:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Scope of the millipayWall plugin:
(function(videojs) {
  // The plugin itself:
  var millipayWall = function(paymentToken) {
    var player = this;
    var wasVideoPayed = false;

    var product = new millipay.Product(paymentToken);
    // When an access authorization was given, disable paywall
    // via `wasVideoPayed = true;` and start the video:
    product.onAccessAuthorization
           .call(function() {
             wasVideoPayed = true;
             player.play();
           });

    // Before the video starts playing, check whether it was
    // already paid, and if not pause video and start payment:
    player.on('play', function() {
      if (!wasVideoPayed) {
        player.pause();
        product.startPayment();
      }
    });
  }

  // Register plugin with videojs:
  videojs.plugin('millipayWall', millipayWall);
}(window.videojs));

var token = "eyJ0eXAiOiJxxxiJ9.eyJwYXlsb2Fkxxxn0.WoXZUORoR7Txxx3Kw";
var product = new millipay.Product(token);
var player = videojs('millipayWallVideo');
// Initialize paywall with payment token:
player.millipayWall(token);