<?php
/**
 * 实名认证分发系统 - PHP SDK
 * 版本: 1.0.0
 */
class AuthSDK {
    private $apiUrl;
    private $appId;
    private $appKey;

    public function __construct($apiUrl, $appId, $appKey) {
        $this->apiUrl = rtrim($apiUrl, '/');
        $this->appId = $appId;
        $this->appKey = $appKey;
    }

    private function sign($params) {
        ksort($params);
        $str = '';
        foreach ($params as $k => $v) {
            if ($k !== 'sign' && $v !== '') {
                $str .= $k . '=' . $v . '&';
            }
        }
        $str .= 'app_key=' . $this->appKey;
        return md5($str);
    }

    public function getBalance() {
        return $this->request('/api/balance');
    }

    public function idcardVerify($name, $idcard) {
        $params = ['name' => $name, 'idcard' => $idcard, 'app_id' => $this->appId, 'timestamp' => time()];
        $params['sign'] = $this->sign($params);
        return $this->request('/api/idcard', $params);
    }

    public function faceVerify($imageBase64, $name, $idcard) {
        $params = ['image_base64' => $imageBase64, 'name' => $name, 'idcard' => $idcard, 'app_id' => $this->appId, 'timestamp' => time()];
        $params['sign'] = $this->sign($params);
        return $this->request('/api/face', $params);
    }

    public function phoneVerify($name, $idcard, $phone) {
        $params = ['name' => $name, 'idcard' => $idcard, 'phone' => $phone, 'app_id' => $this->appId, 'timestamp' => time()];
        $params['sign'] = $this->sign($params);
        return $this->request('/api/phone', $params);
    }

    private function request($path, $params = []) {
        $url = $this->apiUrl . $path;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $result = curl_exec($ch);
        curl_close($ch);
        return json_decode($result, true);
    }
}
