<?php

namespace voice;

class IgrWsDemo
{

    protected $hostUrl; //http url 不支持解析 ws/wss schema
    protected $appid;
    protected $apiSecret;
    protected $apiKey;
    protected $file = "0.pcm";
    protected $statusFirstFrame = 0;
    protected $statusContinueFrame = 1;
    protected $statusLastFrame = 2;

    /**
     * 初始化参数
     * @return mixed
     */
    public function __construct() {
        $this->hostUrl = config("xunfei")["host"];
        $this->appid = config("xunfei")["appid"];
        $this->apiSecret = config("xunfei")["apiSecret"];
        $this->apiKey = config("xunfei")["apiKey"];

    }

    /**
     * 获取鉴权
     */
    public function getAuthorization() {
        // date 格式:UTC+0或GMT时区,RFC1123格式(Mon, 02 Jan 2006 15:04:05 GMT)。
        $date = gmstrftime("%a, %d %b %Y %T %Z",time());

        // 构建 authorization原始参数 注意保留换行符
        $authorization_origin = "host: ".$this->hostUrl."\ndate: ".$date."\nGET /v2/igr HTTP/1.1";
        // 获取签名后的摘要signature_sha。
        // 参考:https://www.it1352.com/1743824.html
        $signature_sha = hash_hmac('sha256', $authorization_origin, $this->apiSecret);

        // base 64 加密
        $signature64 = base64_encode($signature_sha);

        // 构建authorization请求参数
        $authorization = base64_encode('api_key='.$this->apiKey.', algorithm="hmac-sha256", headers="host date request-line", signature='.$signature64);

        $request_url = "wss://ws-api.xfyun.cn/v2/igr?authorization=".$authorization."&date=".$date."&host=".$this->hostUrl;

        return $request_url;
    }

}