<?php
/*
==============================AI写真==============================
*/

$api_url = "https://swapface-api.segapi.com/swapface";
$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);

    $currentTimestamp = time();
    array_push($headers, "X-Ca-Nonce" . ":" . $currentTimestamp); # 本次请求标示 推荐使用uuid

    $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 portrait_ai()
{
    # AI写真接口
    global $api_url, $appcode;;


    $param = [
        "source_url" => "https://ts-mmqi-1259176759.cos.ap-beijing.myqcloud.com/aliyun_api_img/source_img.jpg", # 用户图片
        "target_url" => "https://ts-mmqi-1259176759.cos.ap-beijing.myqcloud.com/aliyun_api_img/target_img.jpg", # 模版图片
        "notify_url" => "https://www.baidu.com" # 回调地址
    ];
    $body = json_encode($param);

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


# AI 写真接口
portrait_ai();

