天天看點

喜馬拉雅資料接口 接入 demo PHP版 API

記錄一下使用經驗,正常參數封裝使用。

API接口版

具體操作類XmlyApi.php

示例,更多需求可前往喜馬拉雅官方文檔查詢,調用方法同理。

<?php

/**
 * author : zhw
 * 2020-03-03
 * 喜馬拉雅認證接口
 */
header('Content-Type:application/json; charset=utf-8');
include_once("xmly.php");

class XmlyApi extends Xmly
{
    public function __construct($get)
    {
        $this->get = $get;
    }

    /**
     * 擷取分類
     */
    public function getCategoriesList()
    {
        $o_url = "/categories/list";
        $parme = array(
            'server_api_version' => '1.0.0',                         //伺服器端API版本号
        );
        $url = $this->createUrl($o_url, $parme);
        $res = json_decode(file_get_contents($url), true);
        var_dump($res);
    }

    /**
     * 擷取專輯
     * @param Int $category_id 分類ID,為0時表示熱門分類。
     * @param Int $calc_dimension 傳回結果排序次元:1-最火,2-最新,3-最多點傳播放
     * @param Int $page 傳回第幾頁,從1開始,預設為1
     * @param Int $count 每頁大小,範圍為[1,200],預設為20
     * @return ArrayObject $res
     */
    public function getAlbumsList($category_id = 6, $calc_dimension = 1, $page = 1, $count = 20)
    {
        $o_url = '/v2/albums/list';
        $category_id = $this->get['category_id'] ? $this->get['category_id'] : 6;
        $page = $this->get['page'];
        $count = $this->get['limit'];
        if (empty($page)) {
            $page = 1;
        }
        if (empty($count)) {
            $count = 20;
        }
        $parme = array(
            'category_id' => $category_id,
            'calc_dimension' => $calc_dimension,
            'page' => $page,
            'count' => $count,
            'server_api_version' => '1.0.0',
        );
        $url = $this->createUrl($o_url, $parme);
        $res = file_get_contents($url);
        echo $res;
    }

    /**
     * 擷取專輯
     * @param Int $ids 以英文逗号分隔的專輯ID,一次最多傳200個,超出部分ID會被忽略
     * @param Boolen $with_metadata true代表傳回metadata,false或不填不傳回,擷取所有中繼資料清單,可以使用接口/metadata/list
     * @return ArrayObject $res
     */
    public function getAlbumsInfo($ids = '29122679,17592887,30589078,245037,', $with_metadata = true)
    {
        $o_url = '/albums/get_batch';
        $parme = array(
            'ids' => $ids,
            'with_metadata' => $with_metadata,
            'server_api_version' => '1.0.0',
        );
        $url = $this->createUrl($o_url, $parme);
        $res = json_decode(file_get_contents($url), true);
        var_dump($res);
    }

    /**
     * 擷取專輯下聲音清單
     * @param SInt $album_id 專輯ID
     * @param Boolean $sort 傳回結果排序方式: "asc" - 喜馬拉雅正序,"desc" - 喜馬拉雅倒序,"time_asc" - 釋出時間升序,"time_desc" - 釋出時間降序,預設為"asc"
     * @param Int $page 傳回第幾頁,從1開始,預設為1
     * @param Int $count 每頁大小,範圍為[1,200],預設為20
     * @return ArrayObject $res
     */
    public function getAlbumsBrowseList($album_id = 35505996, $sort = 'asc', $page = 1, $count = 20)
    {
        $o_url = '/albums/browse';
        $album_id = $this->get['album_id'] ? $this->get['album_id'] : 35505996;
        $page = $this->get['page'];
        $count = $this->get['limit'];
        $parme = array(
            'album_id' => $album_id,
            'sort' => $sort,
            'page' => $page,
            'count' => $count,
            'server_api_version' => '1.0.0',
        );
        $url = $this->createUrl($o_url, $parme);
        $tracks_res = file_get_contents($url);
        $tracks_res = json_decode($tracks_res,true);
        $ids = '';
        foreach($tracks_res['tracks'] as $v){
            $ids .= $v['id'].',';
        }
        $res['tracks_count'] = $tracks_res['total_count'];
        $res['tracks'] = $this->getBatchTracksInfo($ids);
        echo json_encode($res);
    }

    /**
     * 批量擷取聲音資訊
     * @param String $ids 以英文逗号分隔的聲音ID,一次最多傳200個,超出部分ID會被忽略
     * @param Boolean $only_play_info 可選參數,為true時隻傳回音頻播放位址
     * @return ArrayObject $res
     */
    public function getBatchTracksInfo($ids = '270369642,270372994,270372995,270372996', $only_play_info = true)
    {
        $o_url = '/tracks/get_batch';
        $parme = array(
            'ids' => $ids,
            'only_play_info' => $only_play_info,
            'server_api_version' => '',
        );
        $url = $this->createUrl($o_url, $parme);
        $res = json_decode(file_get_contents($url),true);
        return $res;
    }
}

$method = $_GET['method'];
$data = $_GET;
if (!$method) {
    $method = $_POST['method'];
    $data = $_POST;
}
$c = new XmlyApi($data);
if (method_exists($c, $method)) {
    $c->$method();
} else {
    echo 'cess';
}
           

父類xmly.php

主要是生成通路連結等公用方法,包含:sig參數的生成。

<?php

/**
 * author : zhw
 * 2020-03-03
 * 喜馬拉雅認證接口
 */
header('Content-Type:application/json; charset=utf-8');
header('Access-Control-Allow-Origin:*');
//喜馬拉雅開發者背景配置得到參數
define("CLIENT_ID", "2********1");
define("CLIENT_SECRET", "a*****51");
define("CLIENT_STATIC_KEY", "g****P");

class Xmly
{
    public function __construct($get)
    {
    }

    /**
     * createUrl 生成請求連接配接
     * @param String $url
     * @param Array $data
     * @return $tmpInfo
     */
    public function createUrl($o_url, $data)
    {
        if (!$data['device_id']) {
            $rand = rand(1, 99999);
            $data['device_id'] = md5($rand);
        }
        $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'] = $this->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
     */
    public function getMillisecond()
    {
        list($t1, $t2) = explode(' ', microtime());
        return (float) sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }

    /**
     * curl 方法
     * @param String $url
     * @param Array $data
     * @return $tmpInfo
     */

    public 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;
    }
}