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蚕愤、初始化(授權(quán)登錄答恶、免登陸)
config({
app_key: '2e*****1', // 必傳,官方提供的 app_key:b617866c20482d133d5de66fceb37da3 僅供測(cè)試萍诱,有調(diào)用次數(shù)限制悬嗓。
//get_access_token: getAccessToken, // 標(biāo)準(zhǔn)登錄授權(quán),必須傳 get_access_token 參數(shù)裕坊,值為 js 函數(shù)包竹,和 sig_url 互斥
device_id: XMLY.getDeviceId(),
sig_url: 'http******/xmly/jssdk.php', // 免登錄授權(quán),必須傳 sig_url,和 get_access_token 互斥
timeout: 10 * 1000,
debug: true,
})
that.xmly = new XMLY()
// 獲取訪問(wèn)令牌 access_token周瞎,函數(shù)的返回值為字符串(即:access_token 的值)
function getAccessToken() {
// 書(shū)寫(xiě)授權(quán)邏輯
// 確保返回有效的 access_token 值
return 'b7a259c1864cc659ddfdd07910dc75a8' // return 返回有效的 access_token 值
}
免登陸 jssdk.php 獲取前端數(shù)據(jù)進(jìn)行數(shù)據(jù)加密回傳苗缩,喜馬拉雅sdk自行獲取。
<?php
/**
* author : zhw
* 2020-03-03
* 喜馬拉雅jssdk認(rèn)證接口
*/
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;
}
標(biāo)準(zhǔn)登錄 用戶需要調(diào)用喜馬拉雅登錄頁(yè)面二次跳轉(zhuǎn) 回傳地址oauth.php 獲取token
<?php
/**
* author : zhouhongwei
* 2020-03-03
* 喜馬拉雅認(rèn)證接口
*/
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("參數(shù)錯(cuò)誤声诸,請(qǐng)聯(lián)系管理員");
}
$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 生成請(qǐng)求連接
* @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; //客戶端系統(tǒng)類型酱讶,固定值
$data['nonce'] = (string) $rand_only; //設(shè)備唯一碼
$data['timestamp'] = getMillisecond(); //毫秒級(jí)別時(shí)間戳
$data['server_api_version'] = '1.0.0'; //服務(wù)器端API版本號(hào)
//生成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 標(biāo)簽被html頁(yè)面轉(zhuǎn)譯了 如果是用瀏覽器測(cè)試 記得修改一下這個(gè)標(biāo)簽
}
/**
* 時(shí)間戳 - 精確到毫秒
* @return float
*/
function getMillisecond()
{
list($t1, $t2) = explode(' ', microtime());
return (float) sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
}
3、調(diào)接口
<!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;
// // 在盡可能早的時(shí)機(jī)執(zhí)行 config
config({
app_key: '2e8******b751', // 必傳彼乌,官方提供的 app_key:b617866c20482d133d5de66fceb37da3 僅供測(cè)試泻肯,有調(diào)用次數(shù)限制。
//get_access_token: getAccessToken, // 標(biāo)準(zhǔn)登錄授權(quán)慰照,必須傳 get_access_token 參數(shù)灶挟,值為 js 函數(shù),和 sig_url 互斥
device_id: XMLY.getDeviceId(),
sig_url: 'http://****/jssdk.php', // 免登錄授權(quán)毒租,必須傳 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
// 創(chuàng)建實(shí)例
const url = 'https://api.ximalaya.com/categories/list'
// 獲取分類列表
that.xmly.get(url).then(res => {
if (res.code === 0) {
// 成功邏輯(僅成功時(shí) code 為 0)
console.log(res)
that.categoriesArr = res.data
}
// code 可能的值有:0、-1墅垮、-2榛泛、-3、-4
}).catch(error => {
// 為了更易用噩斟,SDK內(nèi)部對(duì)請(qǐng)求的錯(cuò)誤進(jìn)行了捕獲曹锨、分類,然后走的是 resolve
// 所以剃允,開(kāi)發(fā)者調(diào)用 API 時(shí)基本不需要 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)
}
// // 創(chuàng)建播放器實(shí)例
const player = new XMplayer({
playlist: [182847535, 197491263, 183339305, 195901119] // 必傳參數(shù)
})
player.play()
//獲取url參數(shù)
function get_query_string(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg); //search,查詢沛简?后面的參數(shù),并匹配正則
if (r != null) return decodeURI(r[2]);
return null;
}
//設(shè)置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>