1:  2:  3:  4:  5:  6:  7:  8:  9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 
<?php
namespace Comprobo\Verify\Auth;

use Comprobo\Verify\Exceptions;
use Comprobo\Verify\Factory;

/**
 * Server integration for the Authentication microservice
 */
class Server
{
    /**
     * @var Factory
     */
    private $factory;

    /**
     * @var array
     */
    private $config;

    public function __construct(Factory $factory)
    {
        $this->factory = $factory;
        $this->config  = $factory->getConfig();
    }

    /**
     * Calls out to the authentication service using the dedicated
     * integration authorisation route.
     *
     * @param  string $key     your integration key
     * @param  string $secret  your integration secret
     * @return  array $token    the validated response token
     * @throws Exceptions\Auth if your credentials are incorrect or the service returns a malformed response
     */
    public function authenticate($key, $secret)
    {
        $params = [
            'key'    => $key,
            'secret' => $secret
        ];

        $request  = $this->factory->getRequest();
        $response = $request->post($this->config['urls']['auth'], ['json' => $params]);
        $body     = json_decode((string) $response->getBody(), true);

        $token = isset($body['token']) ? $body['token'] : false;

        if ($response->getStatusCode() !== 200 || !$token) {
            throw new Exceptions\Auth("Failed to authenticate");
        }

        return $token;
    }
}