<?php
namespace app\controller;

class Sample
{
    const API_KEY = "6Yijgt5TOXGJ9cxzO3OIx57N";
    const SECRET_KEY = "WgK9ICW5e10mGist2qRlk1comF5YBPhY";

    public function run($filePath)
    {
        //10.jpg  18.png w1.jpeg   w2.jpeg  w3.png w66.jpeg w77.png w222.jpeg  WechatIMG6.jpeg
        $image = file_get_contents($filePath);///

        $image = base64_encode($image);

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://aip.baidubce.com/rest/2.0/ocr/v1/medical_report_detection?access_token={$this->getAccessToken()}",
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_CUSTOMREQUEST => 'POST',

            CURLOPT_POSTFIELDS => http_build_query(array(
                'location' => 'false',
                'probability' => 'false',
                'image' => $image
            )),

            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/x-www-form-urlencoded',
                'Accept: application/json'
            ),

        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }

    /**
     * 使用 AK，SK 生成鉴权签名(Access Token)
     * @return string 鉴权签名信息(Access Token)
     */
    private function getAccessToken()
    {
        $curl = curl_init();
        $postData = array(
            'grant_type' => 'client_credentials',
            'client_id' => self::API_KEY,
            'client_secret' => self::SECRET_KEY
        );
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://aip.baidubce.com/oauth/2.0/token',
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => http_build_query($postData)
        ));
        $response = curl_exec($curl);

        curl_close($curl);
        $rtn = json_decode($response);
        return $rtn->access_token;
    }


}
