<?php
/*
==============================证件照制作换装预览接口-生成带水印预览图接口==============================
*/

$api_url = "https://dresspro.market.alicloudapi.com/preview";
$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 preview_api($photo_path)
{
    # 预览接口
    global $api_url, $appcode;;

    $file_content = file_get_contents($photo_path);
    # 证件照制作或证件照高精细接口返回
    # 衣服模板code


    $param = [
        "photo_key" => "5eac978b90654a9f84689000c7f501a8",
        "dress_code" => "lady001",
        "bk" => "red"
    ];
    $body = json_encode($param);

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


# 换装预览接口
preview_api($photo_file);

