<?php

namespace SRVX\Service\AliBPass\demo;


require_once 'EcoApiClient.php';

use SRVX\Service\BaseService;


class AliEcoService extends BaseService
{

    public $serverUrl = "https://cloudpaygw.alipay-eco.com";
    public $appId = 'app-230801DJKNnkE66EP582nUi9zt6i';
    public $privateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCSGJ9ob4kmGy6y4YeynjKJc/LSg02EXjLErPZSfVrAOy69FTRfBDbazlxpfl6YCAxDdT5ZcspB5kS2XYOY4dmqqPmF4VywmcjmZM8IxZFl1p7YC8BOlP6JrzDPwVl3hn4z3Em1byj8ANLY/AxAaW9W43FSIX+cSfdJThTlxGcbHZFM3kqu++hgFc/E+ar1nB0garqh03ESjatO4b6tuHM57ou7M+fXsoIf3gaL1IDZpeAoRh5sLCBLIbLz55tF0DcOaFsK7NUImnabJDRtrM1IN0lDZkQYAzL+JFsAq+ncRJm60Vd1jq/pXML/cFVHQQgdnjUd2u2NJTSMiCKCftmdAgMBAAECggEARzt+LduEEXJbeJiCI1MC7QX9tSqUFyAevMpgZ6P7JZM1nLfECzfwzwqjAES/Nn1mDVYTCmXvu+XcRtadnWMxUAaHcwGIwgqZa8xnLa220OKuHETOhQIcgWFL+WAakS6gRgT4Y2BJqWV1aJqsFpPR15mZ3SO8JqXhznolsknqw8sO+DBJu+QXn1HdntSGWrLU4GblPlYAs64y/MzPMUWfA4ShDRn9MZK6ypnh2GB5ezgnFxx1jRGOy96IqikI8f+M/CVdgzErLIl+qTd/IbfL8B6Gccb4ZwimL/x1H1bqYCA6xINMZLo5eDHCvBTU4AW7sItw1Q7MQ8l3wBl7hW62gQKBgQDZT1SEaeBtOJxt3vrK7o/kCWNh/4h9oENFhDIuTvLQk9tirKw0BSiZedjbEHqnqM+bgeuvxazCp9uqoYXgC/dtIooy1P8aso+ZrroC/0vZV7TQBGBjbSSkKPn7ShZM2hfYQFpmLznwpel7KJbP6AJ8atv99wjB6uvqNf6fMU7IbQKBgQCsG3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WDn5AwAlzqfOERgLMWD2r6FE8tOXVbMha6IImQIDAQAB'; //平台公钥
    public $aesKey = 'HOrPS0V4BthAPfgSdbHWwy0TwPnC8TQAQZIOjc8vOzI='; //加密密钥
    public $signType = 'RSA2';
    public $format = 'json';
    public $charset = 'UTF-8';



    /**
     * alipay.planet.ecocampus.api.roster.signUpInfo(签约信息同步)
     * @param $face_uid string 学生刷脸编号（不可修改）
     * @param $parent_uid string 家长uid（可修改）    2088122417040252
     * @param $parent_logon_id string 家长支付宝账号脱敏信息（可修改）
     * @param $roster_name string 学生姓名（可修改）
     * @param $out_roster_code string 外部花名册编号（不可修改）
     * @param $school_code string 学校内标（不可修改）
     * @param $school_name string 学校名称（不可修改）
     * @param $face_open_status string 刷脸开通状态（可修改）
     * @param $scan_face_pay_status string 刷脸支付开通状态（可修改）
     * @return array
     */

    public function alipayPlanetEcocampusApiRosterSignUpInfo($face_uid, $parent_uid, $parent_logon_id, $roster_name, $out_roster_code, $school_code, $school_name, $face_open_status = "OFF", $scan_face_pay_status = "OFF"): array
    {

        // cleint初始
        $client = new \EcoApiClient();

        // 根据环境，选择行星OPENAPI网关地址
        $client->gatewayUrl = $this->serverUrl;
        $client->rsaPrivateKey = $this->privateKey;
        $client->alipayrsaPublicKey = $this->alipayPublicKey;
        $client->signType = $this->signType;
        $client->format = $this->format;

        // 业务参数
        $bizContent["face_uid"] = $face_uid;
        $bizContent["parent_uid"] = $parent_uid;
        $bizContent["parentLoginId"] = $parent_logon_id;
        $bizContent["roster_name"] = $roster_name;
        $bizContent["out_roster_code"] = $out_roster_code;
        $bizContent["school_code"] = $school_code;
        $bizContent["school_name"] = $school_name;
        $bizContent["face_open_status"] = $face_open_status;
        $bizContent["scan_face_pay_status"] = $scan_face_pay_status;

        // 指定需要调用的service接口
        $params["service"] = "alipay.planet.ecocampus.api.roster.signUpInfo";
        $params["request_id"] = "" . uuid();
        $params["biz_content"] = json_encode($bizContent);
        $params["version"] = "1.0";

        // 其他参数
        $params["charset"] = $this->charset;
        $params["isv_app_id"] = $this->appId;
        $params["utc_timestamp"] = "" . msectime();

        //获取签名
        $sign = $client->generateSign($params, $this->signType);

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

        var_dump($result);


        $jsonStr = json_encode($result);


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

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

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

        return [];
    }

}


/**
 * 验签 仅支持 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;
}
