<?php
/*
==============================证件照制作高精版获取下载地址==============================
*/


$api_url = "https://idphotohq-open.segapi.com/take";
$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 take_api($photo_key)
{
    # 预览接口
    global $api_url, $appcode;;

    # photo_key来源于"证件照制作高精版预览接口"调用结果
    # 所以要先调用"预览接口"，获取到photo_key后，再调用本"获取下载地址"的接口
    $param = ["photo_key" => $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;
}

# 调用本接口之前需要先调用"证件照制作高精版预览"子接口，
# 从其返回的结果中，获取参数photo_key，
# 然后将其photo_key的值填写到下面的变量中，
# photo_key的有效期为2小时
$photo_key = "从'证件照制作高精版预览接口'调用返回的结果中获取";

take_api($photo_key);


