Your IP : 216.73.216.79


Current Path : /var/www/html/mnrb/backend/modules/cryptoaverage/exchange/
Upload File :
Current File : /var/www/html/mnrb/backend/modules/cryptoaverage/exchange/Helpers.php

<?php

/**
 * Helpers
 */
class Helpers
{

    /**
     * parse body
     */
    public static function parseBody()
    {
        try {
            $raw = file_get_contents('php://input');
            $raw = json_decode($raw);

            if (is_object($raw)) {
                $conf = json_decode(file_get_contents(__DIR__ . '/api.json'));
                // self::stub($raw->data);
                self::checkNonce($conf->api->API_KEY, $raw->nonce, $raw->hash);

                return $raw;
            } else {
                throw new \Exception('Payload other than json will not be accepted');
            }
        } catch (\Exception $e) {
            die(self::error([
                'success' => false,
                'message' => $e->getMessage()
            ]));
        }
    }

    /**
     * send the response
     */
    public function send($data)
    {
        header('Content-type: application/json');

        try {
            echo json_encode($data);
        } catch (\Exception $e) {
            die($e->getMessage());
        }
    }

    /**
     * Send error response
     */
    public static function error($data)
    {
        http_response_code(500);

        die(json_encode($data));
    }

    /**
     * Send success response
     */
    public static function success($data)
    {
        http_response_code(200);
        die(json_encode([
            'success' => 'true',
            'data' => $data
        ]));
    }

    /**
     * check nonce
     */
    public static function checknonce($key, $nonce, $hash)
    {
        if (empty($key)) {
            throw new \Exception('Missing key');
        }

        if (empty($nonce) || empty($hash)) {
            throw new \Exception('Missing nonce or hash');
        }

        if ((time() - $nonce) > 120) { // time out in second
            throw new \Exception('Expired nonce');
        }

        $enc = hash_hmac('sha256', $nonce, $key);

        if (! hash_equals($enc, $hash)) {
            throw new \Exception('Invalid key');
        }
    }

    private static function stub()
    {
        // $nonce = time();
        // $conf = json_decode(file_get_contents(__DIR__ . '/api.json'));
        // $hash = hash_hmac('sha256', $nonce, $conf->api->API_KEY);

        // echo $hash . '|';
        // echo $nonce;
        // die();
    }
}

// init
$helpers = new Helpers();