<?php

require_once '../EcoApiClient.php';

// cleint初始
$client = new EcoApiClient();
// 根据环境，选择行星OPENAPI网关地址
$client->gatewayUrl = 'http://dev-apigw.alipay-eco.com';
$client->rsaPrivateKey = '更换为应用私钥';
$client->alipayrsaPublicKey = '更换为行星平台公钥';
$client->signType = 'RSA2';
$client->format = 'json';


// 业务参数
$bizContent["coachNo"] = "123456";
$bizContent["idCard"] = "320324199901013131";

// 其他参数
$params["charset"] = "UTF-8";
$params["isv_app_id"] = "更换为行星平台APPID";
$params["utc_timestamp"] = "" . msectime();
// 指定需要调用的service接口
$params["service"] = "alipay.planet.footballdc.openapi.coach.sync";
$params["request_id"] = "" . uuid();
$params["biz_content"] = json_encode($bizContent);
$params["version"] = "1.0";

echo "<br/>========== 获取签名 ===========<br/>";
$sign = $client->generateSign($params, "RSA2");
echo "<br/>签名 : $sign <br/>";
echo ("<p>==================================</p>");

// 调用ECOAPI
$result = $client->call($params);

echo "<br/>========== 响应 ===========<br/>";
var_dump($result);

// var_dump(openssl_get_md_methods());


$jsonStr = json_encode($result);


// -- 响应的签名验证 ------
// 转成Array 而非 Object
$resMapData = json_decode($jsonStr, true);

// 验签
$verifyRes = checkResponse($resMapData,$client->alipayrsaPublicKey);

if ($verifyRes) {
    echo "响应验签成功";
} else {
    echo "响应验签失败";
}


/**
 * 验签 仅支持 RSA2
 */
function checkResponse($res, $pubKey)
{

    $resSignType = $res['sign_type'];
    if($resSignType != "RSA2"){
        return false;
    }

    $resSign = $res['sign'];

    $data = $res["response"];
    nestKsort($data);
    $data = json_encode($data,JSON_UNESCAPED_UNICODE);
    $data = str_replace("[]", "{}", $data);

    $pubKey = "-----BEGIN PUBLIC KEY-----\n" .
        wordwrap($pubKey, 64, "\n", true) .
        "\n-----END PUBLIC KEY-----";
    $pubKey = openssl_get_publickey($pubKey);

    $resSign = base64_decode($resSign);
    $result = (bool)openssl_verify($data, $resSign, $pubKey, OPENSSL_ALGO_SHA256);
    return $result;
}

/**
 * 返回值json字段排序
 */
function nestKsort(&$data)
{
    foreach ($data as $key => &$item) {
        if (is_array($item)) {
            nestKsort($item);
        }
    }
    ksort($data);
}


/**
 * 返回当前的毫秒时间戳
 */
function msectime()
{
    list($s1, $s2) = explode(' ', microtime());
    return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
}

/**
 * 生成UUID
 */
function  uuid()
{
    $chars = md5(uniqid(mt_rand(), true));
    $uuid = substr($chars, 0, 8) . '-'
        . substr($chars, 8, 4) . '-'
        . substr($chars, 12, 4) . '-'
        . substr($chars, 16, 4) . '-'
        . substr($chars, 20, 12);
    return $uuid;
}
