玩家管理範例的設定

本頁介紹如何編寫新播放器的基本樣本。這包括有關基本身份驗證的詳細信息,以及在Player Management API示例中如何使用AJAX。

簡介

在逐步中:您使用curl語句與Player管理文檔進行交互的API。進行API調用後,系統會提示您輸入密碼。雖然這對於curl非常有效,但是在構建應用程序時這種交互式身份驗證是不可行的。

在這裡,您將學習如何使用JavaScript和XMLHttpRequest(也稱為AJAX)發出API請求,以構建用於播放器管理操作的Web客戶端。

因為播放器管理API是啟用CORS並允許使用您的Brightcove登錄憑據進行基本身份驗證,就像在Player Management API示例中一樣,可以直接從網頁發出API請求。Brightcove的其他RESTful API需要通過以下方式進行身份驗證OAuth。由於用於檢索訪問令牌的API未啟用CORS(API本身也未啟用),因此您必須通過服務器端應用程序發出請求。看到使用REST API獲取有關使用Web UI和代理訪問REST API來構建混合應用程序的指南。對於在生產環境中也使用Player Management API的應用程序,我們也建議使用這種方法,因為它更安全,不會通過HTTP連接發送任何憑據。

基本認證

在逐步中:您使用curl語句與Player管理文檔進行交互的API。進行API調用後,系統會提示您輸入密碼。雖然這對於curl非常有效,但是在構建應用程序時這種交互式身份驗證是不可行的。

您可以在構建應用程序時使用基本身份驗證。在標頭中,您需要發送憑據,並以64位編碼的ASCII字符串加密。您可以使用JavaScript btoa()進行編碼的方法。假設account_usernameaccount_password從(例如)表單填充時,Authorization標頭將顯示如下:

     "Authorization": "Basic " + btoa(account_username + ":" + account_password),

AJAX

這些示例將使用JavaScript與API通信,而不是使用curl語句。這意味著使用AJAX將請求發佈到API。一個特定的示例請求可能看起來像這樣:

    $.ajax({
        type: "DELETE",
        headers: {
        "Authorization": "Basic " + btoa("username:password"),
        "Content-Type": "application/json"
        },
        url: "https://players.api.brightcove.com/v2/accounts/123456789/players/478772a5-a2f2-44c6-a26b-2d7234bd97f5",
        success: ajaxSuccess,
        error: ajaxError
    });

關聯的successerror處理程序可能看起來像這樣:

    var ajaxSuccess = function (data) {
        document.getElementById("jsonResponse").innerHTML = JSON.stringify(data,null,2);
        };
    
        var ajaxError = function (data) {
        console.log("error data: ");
        console.log(data);
    };

當然,您不想像上面所示那樣對AJAX調用中的所有信息進行硬編碼,因此有意義的是將實際調用抽象為可重用的函數,如下所示:

    var makeAjaxCall = function (callURL, callType, callData) {
        if (callData) {
            $.ajax({
                type: callType,
                headers: {
                    "Authorization": "Basic " + btoa(account_username + ":" + account_password),
                    "Content-Type": "application/json"
                },
                url: callURL,
                data: JSON.stringify(callData),
                success: ajaxSuccess,
                error: ajaxError
            });
        } else {
            $.ajax({
            type: callType,
            headers: {
                "Authorization": "Basic " + btoa(account_username + ":" + account_password),
                "Content-Type": "application/json"
            },
            url: callURL,
            success: ajaxSuccess,
            error: ajaxError
            });
        }
    };

然後您就可以調用該函數了。在以下示例中account_idaccount_passwordaccount_username值均從表單中提取。

    var getPlayerInfo = function () {
        account_id = document.getElementById("account_id").value,
        account_password = document.getElementById("account_password").value,
        account_username = document.getElementById("account_username").value;
        call_url = "https://players.api.brightcove.com/v2/accounts/" + account_id + "/players";
        makeAjaxCall(call_url, "GET", null);
    };

如果您已完成分步操作:您已經知道播放器管理文檔,其中有些過程需要多個API調用,例如創建和發布播放器。同樣,某些應用程序的邏輯可能需要多次API調用,例如獲取要顯示的所有播放器的列表,然後刪除用戶標記的播放器。在這些情況下,您很可能需要更改您的success處理程序根據剛剛成功執行的調用執行不同的邏輯。在這些示例應用中,將使用標誌變量來實現這些用例的實現邏輯,callPurposecase使用該標誌的語句,如下所示:

    var ajaxSuccess = function (data) {
        switch (callPurpose) {
            case "getPlayers":
                createCheckboxes(data);
                watchCheckboxes();
                break;
            case "deletePlayer":
                document.getElementById("jsonResponse").textContent += data;
                break;
        }
    };

沒有jQuery的AJAX

如果您不想使用jQuery,則發出AJAX請求會稍微複雜一點,但不會太多。這是一些示例代碼,帶有註釋,可以幫助您入門:

    /**
     * createRequest sets up requests, send them to makeRequest(), and handles responses
     * @param  {string} type the request type
     */
    function createRequest(type) {
        var options   = {},
            baseURL = 'https://players.api.brightcove.com/v2/accounts/',
            account_id = '1234567890',
            // would be better to get these from form fields
            // and not hardcode them
            username = 'jane@myplace.com',
            password = 'mypassword',
            responseDecoded;
    
        // set credentials
        options.client_id     = cid.value;
        options.client_secret = secret.value;
    
        switch (type) {
            case 'getPlayers':
                options.url         = ipBaseURL + account_id + '/players';
                options.requestType = 'GET';
                options.username = username;
                options.password = password;
                makeRequest(options, function(response) {
                    // use try catch in case something went wrong
                    try {
                        responseDecoded = JSON.parse(response);
                        // now do whatever you want with the response
                    }
                    catch (e) {
                        console.log('something went wrong - this was the JSON.parse error: ' + e);
                    }
                });
                break;
            // additional cases
            default:
                console.log('Should not be getting to the default case - bad request type sent');
                break;
        }
    }
    
    /**
     * send API request
     * @param  {Object} options for the request
     * @param  {String} options.url the full API request URL
     * @param  {String="GET","POST","PATCH","PUT","DELETE"} requestData [options.requestType="GET"] HTTP type for the request
     * @param  {String} options.username username for the account
     * @param  {String} options.password password for the account
     * @param  {JSON} [options.requestBody] Data (if any) to be sent in the request body in the form of a JSON string
     * @param  {Function} [callback] callback function that will process the response
     */
    function makeRequest(options, callback) {
        var httpRequest = new XMLHttpRequest(),
            response,
            requestParams,
            dataString,
            // response handler
            getResponse = function() {
                try {
                    if (httpRequest.readyState === 4) {
                        // don't just check for status = 200
                        // some requests return other 2xx codes
                        if (httpRequest.status >= 200 && httpRequest.status < 300) {
                            response = httpRequest.responseText;
                            // return the response to the callback
                            callback(response);
                        } else {
                            alert('There was a problem with the request. Request returned ' + httpRequest.status);
                        }
                    }
                } catch (e) {
                    alert('Caught Exception: ' + e);
                }
            };
        /**
         * set up request data
         */
        // set response handler
        httpRequest.onreadystatechange = getResponse;
        // open the request
        httpRequest.open(options.requestType, options.url);
        // set headers
        httpRequest.setRequestHeader("Content-Type", "application/json");
        httpRequest.setRequestHeader("Authorization", "Basic " + btoa(options.username + ":" + options.password));
        // open and send request
        if (options.requestBody) {
            httpRequest.send(options.requestBody)
        } else {
            httpRequest.send();
        }
    }