<?php
/*
==============================证件照清晰化==============================
*/

$api_url = "https://ienhance.market.alicloudapi.com/idphoto/enhance";
$appcode = "你的appcode"; # appcode获取方式参考：https://help.aliyun.com/document_detail/157953.html

function http_call($url, $body, $appcode)
{
    $method = "POST";
    $headers = array();
    array_push($headers, "Authorization:APPCODE " . $appcode);
    # 根据API的要求，定义相对应的Content-Type
    array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
    # 一定要在headers中加入Content-MD5头信息
    $content_md5 = base64_encode(md5($body, true));
    array_push($headers, "Content-MD5".":".$content_md5);

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

    curl_setopt($curl, CURLOPT_POSTFIELDS, $body);

    $response = curl_exec($curl);
    $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
    $resp_body = substr($response, $header_size);
    if ($status_code != 200) {
        $resp_headers = substr($response, 0, $header_size);
        $resp_headers = explode("\r\n", $resp_headers);
        foreach ($resp_headers as $header) {
            if (stripos($header, "X-Ca-Error-Message") === 0) {
                print("ali api gateway return error:\n    ".$header."\n");
                return false;
            }
        }
        if ($resp_body) {
            print("server return error:\n    ".$resp_body."\n");
        }
        return false;
    }

    curl_close($curl);
    return json_decode($resp_body, true);
}

function idphoto_enhance_api()
{
    global $api_url, $appcode;;

    $param = [
        "photo_key" => "bd521744960d489d948e2cabf9e1bc33", # photo_key为从“证件照制作接口”或者“更换背景接口”返回的
    ];
    $body = json_encode($param);

    $result = http_call($api_url, $body, $appcode);
    if ($result == false) {
        return false;
    }
    $data = $result["data"];
    var_dump($data);
    return true;
}



idphoto_enhance_api();
