美文网首页
接入喜马拉雅数据 JSSDK API demo WEB版 标准

接入喜马拉雅数据 JSSDK API demo WEB版 标准

作者: 阿_莫西林 | 来源:发表于2020-05-12 15:33 被阅读0次

    1、引入jssdk

    config, XMLY, XMplayer 喜马拉雅sdk封装好的

    <script src="https://s1.xmcdn.com/yx/web-jssdk/last/dist_cdn/1.3.4/xmsdk.min.js"></script>
    

    2、初始化(授权登录、免登陆)

    config({
            app_key: '2e*****1', // 必传,官方提供的 app_key:b617866c20482d133d5de66fceb37da3 仅供测试,有调用次数限制。
            //get_access_token: getAccessToken, // 标准登录授权,必须传 get_access_token 参数,值为 js 函数,和 sig_url 互斥
            device_id: XMLY.getDeviceId(),
            sig_url: 'http******/xmly/jssdk.php', // 免登录授权,必须传 sig_url,和 get_access_token 互斥
            timeout: 10 * 1000,
            debug: true,
    })
    that.xmly = new XMLY()
     
    // 获取访问令牌 access_token,函数的返回值为字符串(即:access_token 的值)
    function getAccessToken() {
        // 书写授权逻辑
        // 确保返回有效的 access_token 值
        return 'b7a259c1864cc659ddfdd07910dc75a8' // return 返回有效的 access_token 值
    }
    

    免登陆 jssdk.php 获取前端数据进行数据加密回传,喜马拉雅sdk自行获取。

    <?php
     
    /**
     * author : zhw 
     * 2020-03-03 
     * 喜马拉雅jssdk认证接口
     */
    header('Content-Type:application/json; charset=utf-8');
    header('Access-Control-Allow-Origin:*');
    define("CLIENT_ID", "2e********751");
    define("CLIENT_SECRET", "a5b******51");
    define("CLIENT_STATIC_KEY", "g***7P");
    $params = $_POST['params'];
    $nonce = isset($_POST['nonce']) ? $_POST['nonce'] : "";
    $device_id = isset($_POST['device_id']) ? $_POST['device_id'] : "";
    $params_arr = json_decode($params, true);
    $sig = createSig($params_arr);
    $d = array(
        'code' => 1,
        'message' => "success",
        'signature' => $sig
    );
    echo json_encode($d);
     
    /**
     * sig 生成
     */
    function createSig($data)
    {
        ksort($data);
        $parme = "";
        foreach ($data as $k => $v) {
            $parme .= "$k=$v&";
        }
        $parme = trim($parme, '&');
        $str = base64_encode($parme);
        $hashKey = CLIENT_SECRET;
        $sigStr = md5(hash_hmac('sha1', $str, $hashKey, true));
        return $sigStr;
    }
    

    标准登录 用户需要调用喜马拉雅登录页面二次跳转 回传地址oauth.php 获取token

    <?php
     
    /**
     * author : zhouhongwei 
     * 2020-03-03 
     * 喜马拉雅认证接口
     */
    header('Content-Type:application/json; charset=utf-8');
     
    define("CLIENT_ID", "2e***51");
    define("CLIENT_SECRET", "a5***1");
    define("CLIENT_STATIC_KEY", "gu**P");
    $backurl = $_GET['state'];
    $code = isset($_GET['code']) ? $_GET['code'] : "";
    $device_id = isset($_GET['device_id']) ? $_GET['device_id'] : "";
    if (!$code || !$device_id) {
        die("参数错误,请联系管理员");
    }
    $data = array(
        'client_id' => CLIENT_ID,
        'client_secret' => CLIENT_SECRET,
        'device_id' => $device_id,
        'grant_type' => 'authorization_code',
        'code' => $code,
        'redirect_uri' => 'http://w***y/oauth.php'
    );
     
    $xmly_url = 'https://api.ximalaya.com/oauth2/v2/access_token';
    $res = curl($xmly_url, $data);
    var_dump($res);
     
     
    /**
     * curl 方法
     * @param String $url 
     * @param Array $data
     * @return $tmpInfo
     */
     
    function curl($url, $data = null)
    {
        $ch = curl_init();
        $header = array("Content-Type:application/x-www-form-urlencoded");
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            return curl_error($ch);
        }
        curl_close($ch);
        return $tmpInfo;
    }
     
     
     
    /**
     * createUrl 生成请求连接
     * @param String $url 
     * @param Array $data
     * @return $tmpInfo
     */
    function createUrl($o_url, $data)
    {
        $url = "https://api.ximalaya.com{$o_url}?";
        $rand_only = time() . rand(1, 9999);
        $data['app_key']            = CLIENT_ID;
        $data['client_os_type']     = 4;                               //客户端系统类型,固定值
        $data['nonce']              = (string) $rand_only;             //设备唯一码
        $data['timestamp']          = getMillisecond();                 //毫秒级别时间戳
        $data['server_api_version'] = '1.0.0';                         //服务器端API版本号
        //生成sign
        ksort($data);
        $parme = "";
        foreach ($data as $k => $v) {
            $parme .= "$k=$v&";
        }
        $parme = trim($parme, '&');
        $str = base64_encode($parme);
        $hashKey = CLIENT_SECRET . CLIENT_STATIC_KEY;
        $sigStr = "&sig=" . md5(hash_hmac('sha1', $str, $hashKey, true));
        $url .= $parme . $sigStr;
        return $url;                                               //生成的url的timestamp 标签被html页面转译了 如果是用浏览器测试 记得修改一下这个标签                           
     
    }
     
    /**
     * 时间戳 - 精确到毫秒
     * @return float
     */
    function getMillisecond()
    {
        list($t1, $t2) = explode(' ', microtime());
        return (float) sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }
     
    

    3、调接口

    <!doctype html>
    <html>
     
    <head>
        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0" />
        <script src="jquery_172.js" language="javascript"></script>
        <script src="https://s1.xmcdn.com/yx/web-jssdk/last/dist_cdn/1.3.4/xmsdk.min.js"></script>
        <script src="https://cdn.bootcss.com/vue/2.5.2/vue.min.js"></script>
        <title>喜马拉雅JSSDK接入</title>
        <style type="text/css">
     
        </style>
    </head>
     
    <body>
        <div id="main">
            <div>
                <h4>分类列表</h4>
                <div style="width: 160px; float: left;" v-for="item in categoriesArr">
                    {{item.id}}:{{item.category_name}}
                    <img style="width: 20px;" :src="item.cover_url_small" />
                </div>
            </div>
     
        </div>
    </body>
    <script type="text/javascript">
        const xmly_did = "XIMALAYA_DEVICEID"
        const { config, XMLY, XMplayer } = window.xmsdk
        var main = new Vue({
            el: '#main',
            data: {
                user_id: Number,
                categoriesArr: Object
            },
            created() {
                var that = this;
                // // 在尽可能早的时机执行 config
                config({
                    app_key: '2e8******b751', // 必传,官方提供的 app_key:b617866c20482d133d5de66fceb37da3 仅供测试,有调用次数限制。
                    //get_access_token: getAccessToken, // 标准登录授权,必须传 get_access_token 参数,值为 js 函数,和 sig_url 互斥
                    device_id: XMLY.getDeviceId(),
                    sig_url: 'http://****/jssdk.php', // 免登录授权,必须传 sig_url,和 get_access_token 互斥
                    timeout: 10 * 1000,
                    debug: true,
                })
                that.xmly = new XMLY()
            },
            beforeMount() {
                var that = this
                that.getCategoriesList()
                
     
            },
            methods: {
                getCategoriesList() {
                    var that = this
                    // 创建实例
                    const url = 'https://api.ximalaya.com/categories/list'
                    // 获取分类列表
                    that.xmly.get(url).then(res => {
                        if (res.code === 0) {
                            // 成功逻辑(仅成功时 code 为 0)
                            console.log(res)
                            that.categoriesArr = res.data
                        }
                        // code 可能的值有:0、-1、-2、-3、-4
                    }).catch(error => {
                        // 为了更易用,SDK内部对请求的错误进行了捕获、分类,然后走的是 resolve
                        // 所以,开发者调用 API 时基本不需要 catch 
                        console.log(error)
                    }).finally(() => {
                        // 其它
                    })
                }
            }
        })
        
        //保存deviceId
        var deviceId = getCookie(xmly_did)
        if (!deviceId) {
            const deviceId = XMLY.getDeviceId()
            setCookie(xmly_did, deviceId, 365)
            console.log(deviceId)
        }
     
        // // 创建播放器实例
        const player = new XMplayer({
            playlist: [182847535, 197491263, 183339305, 195901119] // 必传参数
        })
        player.play()
        //获取url参数
        function get_query_string(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg); //search,查询?后面的参数,并匹配正则
            if (r != null) return decodeURI(r[2]);
            return null;
        }
     
        //设置cookie
        function setCookie(cname, cvalue, exdays) {
            var d = new Date();
            d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
            var expires = "expires=" + d.toUTCString();
            document.cookie = cname + "=" + cvalue + "; " + expires;
        }
     
        //获取cookie
        function getCookie(cname) {
            var name = cname + "=";
            var ca = document.cookie.split(";");
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == " ") c = c.substring(1);
                if (c.indexOf(name) != -1) {
                    return c.substring(name.length, c.length);
                }
            }
            return "";
        }
        //清除cookie
        function clearCookie(cname) {
            this.setCookie(cname, "", -1);
        }
    </script>
     
    </html>
    

    相关文章

      网友评论

          本文标题:接入喜马拉雅数据 JSSDK API demo WEB版 标准

          本文链接:https://www.haomeiwen.com/subject/fjibnhtx.html