漏刻有时API接口实战开发系列(4):萤石云HTTP接口API开发获取accessToken(php)

使用ajax获取萤石云的accessToken时,appKey和secret直接暴露在前端HTML代码中,且success返回的accessToken在异步的情况下,无法作为全局变量使用。为此,在后端中获取accessToken,是非常必要的。

$curl函数封装;

//封装POST函数;
function posturl($url, $data)
{
    //把数组形式的参数转为‘appkey=....&secret=...'这种形式;
    $data = http_build_query($data);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    //输出结果;
    return json_decode($output, true);
}

参数设置

//调用URL;
$url = "https://open.ys7.com/api/lapp/token/get";
//请求参数;
$data = ["appKey" => "bcb59***", "appSecret" => "a749326a19***"];

获取accessToken

//01.获取accessToken
$content = posturl($url, $data);
$accessToken = $content["data"]["accessToken"];

使用accessToken

//02.获取设备列表;
//调用URL;
$url1 = "https://open.ys7.com/api/lapp/device/list";
//请求参数;
$data1 = ["accessToken" => $accessToken];

$content1 = posturl($url1, $data1);
echo "<pre>";
var_dump($content1);

Done!

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页