科大讯飞 鉴权教程

发布于:2024-09-18 ⋅ 阅读:(139) ⋅ 点赞:(0)
<?php

// 定义HmacWithShaTobase64函数,用于生成HMAC-SHA256签名并进行base64编码
function HmacWithShaTobase64($algo, $data, $key) {
    return base64_encode(hash_hmac('sha256', $data, $key, true));
}

// 模拟assembleAuthUrl函数的功能
function assembleAuthUrl($hosturl, $apiKey, $apiSecret) {
    // 解析hosturl
    $urlComponents = parse_url($hosturl);
    $host = $urlComponents['host'];
    $path = $urlComponents['path'];

    // 签名时间
    $date = gmdate('D, d M Y H:i:s \G\M\T');

    // 构建参与签名的字段
    $signString = "host: $host\n";
    $signString .= "date: $date\n";
    $signString .= "GET $path HTTP/1.1";

    // 生成签名
    $sha = HmacWithShaTobase64("hmac-sha256", $signString, $apiSecret);

    // 构建请求参数
    $authUrl = "api_key=\"$apiKey\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"$sha\"";

    // 将请求参数进行base64编码
    $authorization = base64_encode($authUrl);

    // 构建请求URL
    $queryParams = http_build_query(array(
        'host' => $host,
        'date' => $date,
        'authorization' => $authorization
    ));

    $callurl = $hosturl . '?' . $queryParams;
    return $callurl;
}

// 调用assembleAuthUrl函数并输出生成的URL
$hosturl = 'wss://iat-api.xfyun.cn/v2/iat';
$apiKey = '你的key';
$apiSecret = '你的Secret';

$generatedUrl = assembleAuthUrl($hosturl, $apiKey, $apiSecret);
echo $generatedUrl;

?>

将上述代码中的
$apiKey = ‘你的key’;
$apiSecret = ‘你的Secret’;
替换成你的,然后服务器访问PHP,即可获的鉴权的连接,直接连接,即可连接到websocket服务器


网站公告

今日签到

点亮在社区的每一天
去签到