PHP版微信權限驗證配置,音頻文件下載,FFmpeg轉碼,上傳OSS和刪除轉存服務器本地文件

1、概述和經過config接口注入權限驗證配置

因爲微信的臨時素材(如:錄音文件)上傳到微信服務器上,微信後臺保存時間爲3天。而咱們須要長期保存,咱們須要把資源從微信服務器轉存到本身服務器,或者阿里雲OSS/七牛雲。html

微信:新增臨時素材redis

經過config接口注入權限驗證配置:
步驟三:經過config接口注入權限驗證配置json

/**
 * 微信JS-SDK權限驗證配置
 * 
 * @return array
 */
public function getSignPackage() {
    (new SignPackage())->goCheck();
    $url = input('get.url');
    $jsapiTicket = $this->getJsApiTicket();
    $nonceStr = getRandChar(16);
    $timestamp = time();

    $signature = $this->getSignature($jsapiTicket,$nonceStr,$timestamp,$url);

    $signPackage = array(
        "appId"     => config('wx.g_app_id'),
        "nonceStr"  => $nonceStr,
        "timestamp" => $timestamp,
        "signature" => $signature,
        'expire_id' => config('setting.access_token_expire_in'),
        'url'       => $url
    );
    return $signPackage;
}

/**
 * 獲取簽名
 * 
 * @param $jsapiTicket
 * @param $nonceStr
 * @param $timestamp
 * @param $url
 * @return string
 */
private  function getSignature($jsapiTicket,$nonceStr,$timestamp,$url)
{
    // 這裏參數的順序要按照 key 值 ASCII 碼升序排序
    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

    $signature = sha1($string);

    return $signature;
}

/**
 * 獲取臨時票據
 * {
 * "errcode": 0,
 * "errmsg": "ok",
 * "ticket": "kgt8ON7yVITDhtdwci0qeS9ULEKIkoU74AB_VMOQrWUhbW12MQht4FiX4qLA9Z5puKabs96SARo5f1bylEvwXw",
 * "expires_in": 7200
 * }
 * @return mixed
 * @throws Exception
 * @throws ParameterException
 */
private function getJsApiTicket() {

    $access_token = $this->getAccessToken();
    $wxJSapiTicketUrl = sprintf(config('wx.jsapi_ticket'), $access_token);

    $result = curl_get($wxJSapiTicketUrl);
    $wxResult = json_decode($result, true);

    if (empty($wxResult)) {

        throw new Exception('微信內部錯誤');

    }else if ($wxResult['errmsg'] != 'ok'){
        throw new ParameterException([
            'errorCode' => $wxResult['errcode'],
            'msg' => $wxResult['errmsg']
        ]);
    };

    return $wxResult['ticket'];
}

2、獲取media_id

微信JS-SDK說明文檔api

3、根據media_id下載錄音文件

獲取臨時素材服務器

/**
 * 獲取訪問微信接口的access_token
 * 
 * @return mixed
 */
public function getAccessToken()
{
    $redis = Cache::store('redis');
    $wx_access_token = $redis->get('wx_access_token');
    if (!$wx_access_token){
        $access_token = $this->getWXAccessToken();
    }else{
        $access_token = $wx_access_token;
    }

    return $access_token;
}
/**
     * 根據URL地址,下載文件
     *
     * @param $url
     * @param $savePath
     */
    public function downAndSaveFile($url,$savePath)
    {
        ob_start();
        readfile($url);
        $img  = ob_get_contents();
        ob_end_clean();
        $size = strlen($img);
        $fp = fopen($savePath, 'a');
        fwrite($fp, $img);
        fclose($fp);
    }

4、FFmpeg將amr格式音頻文件轉換未mp3格式

PHP 將amr音頻文件轉換爲mp3格式微信

/**
 * 將amr格式轉換成mp3格式
 *
 * @param $amr
 * @param $prefix_filename
 * @return mixed
 */
public function amrTransCodingMp3($amr, $prefix_filename)
{
    $msgId = $prefix_filename;
    $mp3 = $msgId.'.mp3';
    $dir = $_SERVER['DOCUMENT_ROOT'].'/static/audio/';

    exec("ffmpeg -y -i ".$dir.$amr." ".$dir.$mp3);
    return $mp3;
}

5、將轉碼後MP3文件上傳至OSS

阿里雲OSS視頻上傳概述
PHP-SDK上傳文件app

/**
 * 上傳指定的本地文件內容
 *
 * @param OssClient $ossClient OSSClient實例
 * @param string $bucket 存儲空間名稱
 * @param string $object 名字
 * @return mixed
 */
function uploadFile($ossClient, $bucket, $object)
{
    $filePath = $_SERVER['DOCUMENT_ROOT'].'/static/audio/'.$object;

    try{
        $res = $ossClient->uploadFile($bucket, $object, $filePath);
        return $res;
    } catch(OssException $e) {
        return [
            'error' => 'FAILED',
            'msg'   => $e->getMessage()
        ];
    }
}

注:
坑一:貌似服務端只有JAVA的,其實經過PHP-SDK也是能夠經過上傳文件來上傳音頻文件。curl


坑二測試

6、刪除本地文件

因爲我把微信音頻文件存到阿里雲OSS,因此將從微信服務器下載的amr和轉碼的mp3兩個音頻文件刪除。this

/**
 * 刪除本地音頻文件
 *
 * @param $filename
 * @return bool
 * @throws ParameterException
 */
public function deleteDownloadFile($filename)
{
    $filename = $_SERVER['DOCUMENT_ROOT'].'/static/audio/'.$filename;
    if (!unlink($filename))
    {
        throw new ParameterException([
            'msg' => "Error deleting $filename"
        ]);
    }
    else
    {
        return true;
    }
}

7、測試樣例

微信錄音時長最多爲60s,經測試H5端錄音60s語音後,後臺下載,轉碼後以下圖:

而後將mp3文件上傳OSS後返回給客戶端以下:

{
    "server": "AliyunOSS",
    "date": "Mon, 09 Oct 2017 05:52:28 GMT",
    "content-length": "0",
    "connection": "keep-alive",
    "x-oss-request-id": "59DB0E9BE8DFE89CE466195A",
    "etag": "\"A6D50FD012FE2C6AA03EBF38CE23BEEB\"",
    "x-oss-hash-crc64ecma": "8903374940512099110",
    "content-md5": "ptUP0BL+LGqgPr84ziO+6w==",
    "x-oss-server-time": "243",
    "info": {
        "url": "http://xds-test.oss-cn-beijing.aliyuncs.com/wx_download_2017100913522559db0e99d3420.mp3",
        "content_type": null,
        "http_code": 200,
        "header_size": 335,
        "request_size": 472,
        "filetime": -1,
        "ssl_verify_result": 0,
        "redirect_count": 0,
        "total_time": 0.250512,
        "namelookup_time": 0.001418,
        "connect_time": 0.004533,
        "pretransfer_time": 0.004535,
        "size_upload": 60309,
        "size_download": 0,
        "speed_download": 0,
        "speed_upload": 240742,
        "download_content_length": 0,
        "upload_content_length": 60309,
        "starttransfer_time": 0.007707,
        "redirect_time": 0,
        "redirect_url": "",
        "primary_ip": "59.110.185.134",
        "certinfo": [],
        "method": "PUT"
    },
    "oss-request-url": "http://xds-test.oss-cn-beijing.aliyuncs.com/wx_download_2017100913522559db0e99d3420.mp3",
    "oss-redirects": 0,
    "oss-stringtosign": "PUT\n\naudio/mpeg\nMon, 09 Oct 2017 05:52:27 GMT\n/xds-test/wx_download_2017100913522559db0e99d3420.mp3",
    "oss-requestheaders": {
        "Accept-Encoding": "",
        "Content-Type": "audio/mpeg",
        "Date": "Mon, 09 Oct 2017 05:52:27 GMT",
        "Host": "xds-test.oss-cn-beijing.aliyuncs.com",
        "Authorization": "OSS LTAIiKza8Qoz9q4A:PB8WBZp75iaN/pvpbIewFs3Rn08="
    },
    "body": false,
    "process_time": "2.2304130s"
}

從返回process_time來看,從客戶端請求到最後返回給客戶端,60s音頻後臺大概須要處理2.3秒左右(根據服務器配置而不一樣)。

參考資料以下:

微信jssdk錄音功能開發記錄
PHP 將amr音頻文件轉換爲mp3格式

相關文章
相關標籤/搜索