Api.php 15.6 KB
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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
<?php /** @noinspection PhpUnusedParameterInspection */

namespace Ekyna\Component\Payum\Payzen\Api;

use Payum\Core\Exception\LogicException;
use Payum\Core\Exception\RuntimeException;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class Api
 * @package Ekyna\Component\Payum\Payzen\Api
 * @author  Etienne Dauvergne <contact@ekyna.com>
 */
class Api
{
    /**
     * @var OptionsResolver
     */
    private $configResolver;

    /**
     * @var OptionsResolver
     */
    private $requestOptionsResolver;

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


    /**
     * Configures the api.
     *
     * @param array $config
     */
    public function setConfig(array $config)
    {
        $this->config = $this
            ->getConfigResolver()
            ->resolve($config);
    }

    /**
     * Returns the next transaction id.
     *
     * @return string
     */
    public function getTransactionId()
    {
        $path = $this->getDirectoryPath() . 'transaction_id';

        // Create file if not exists
        if (!file_exists($path)) {
            touch($path);
            chmod($path, 0600);
        }

        $date = (new \DateTime())->format('Ymd');
        $fileDate = date('Ymd', filemtime($path));
        $isDailyFirstAccess = ($date != $fileDate);

        // Open file
        $handle = fopen($path, 'r+');
        if (false === $handle) {
            throw new RuntimeException('Failed to open the transaction ID file.');
        }
        // Lock File
        if (!flock($handle, LOCK_EX)) {
            throw new RuntimeException('Failed to lock the transaction ID file.');
        }

        $id = 1;
        // If not daily first access, read and increment the id
        if (!$isDailyFirstAccess) {
            $id = (int)fread($handle, 6);
            $id++;
        }

        // Truncate, write, unlock and close.
        fseek($handle, 0);
        ftruncate($handle, 0);
        fwrite($handle, (string)$id);
        fflush($handle);
        flock($handle, LOCK_UN);
        fclose($handle);

        if ($this->config['debug']) {
            $id += 89000;
        }

        return str_pad($id, 6, '0', STR_PAD_LEFT);
    }

    /**
     * Creates the request url.
     *
     * @param array $data
     *
     * @return string
     */
    public function createRequestUrl(array $data)
    {
        $this->ensureApiIsConfigured();

        $data = $this->createRequestData($data);

        $url = $this->getUrl() . '?' .
            implode('&', array_map(function ($key, $value) {
                return $key . '=' . rawurlencode($value);
            }, array_keys($data), $data));

        return $url;
    }

    /**
     * Creates the request data.
     *
     * @param array $data
     *
     * @return array
     */
    public function createRequestData(array $data)
    {
        $data = $this
            ->getRequestOptionsResolver()
            ->resolve(array_replace($data, [
                'vads_version'     => 'V2',
            ]));

        $data = array_filter($data, function ($value) {
            return null !== $value;
        });

        $data['vads_site_id'] = $this->config['site_id'];
        $data['vads_ctx_mode'] = $this->config['ctx_mode'];

        $data['signature'] = $this->generateSignature($data);

        return $data;
    }

    /**
     * Checks the response signature.
     *
     * @param array $data
     *
     * @return bool
     */
    public function checkResponseIntegrity(array $data)
    {
        if (!isset($data['signature'])) {
            return false;
        }

        return $data['vads_site_id'] === (string)$this->config['site_id']
            && $data['vads_ctx_mode'] === (string)$this->config['ctx_mode']
            && $data['signature'] === $this->generateSignature($data);
    }

    /**
     * Generates the signature.
     *
     * @param array $data
     * @param bool  $hashed
     *
     * @return string
     */
    public function generateSignature(array $data, $hashed = true)
    {
        ksort($data);

        $content = "";
        foreach ($data as $key => $value) {
            if (substr($key, 0, 5) == 'vads_') {
                $content .= $value . '+';
            }
        }

        $content .= $this->config['certificate'];

        if ($hashed) {
            return $this->hash($content);
        }

        return $content;
    }

    /**
     * Returns the directory path and creates it if not exists.
     *
     * @return string
     */
    private function getDirectoryPath()
    {
        $path = $this->config['directory'];

        // Create directory if not exists
        if (!is_dir($path)) {
            mkdir($path, 0755, true);
        }

        return $path . DIRECTORY_SEPARATOR;
    }

    /**
     * Check that the API has been configured.
     *
     * @throws LogicException
     */
    private function ensureApiIsConfigured()
    {
        if (null === $this->config) {
            throw new LogicException('You must first configure the API.');
        }
    }

    /**
     * Returns the config option resolver.
     *
     * @return OptionsResolver
     */
    private function getConfigResolver()
    {
        if (null !== $this->configResolver) {
            return $this->configResolver;
        }

        $resolver = new OptionsResolver();
        $resolver
            ->setRequired([
                'site_id',
                'certificate',
                'ctx_mode',
                'directory',
            ])
            ->setDefaults([
                'endpoint' => null,
                'debug'    => false,
            ])
            ->setAllowedTypes('site_id', 'string')
            ->setAllowedTypes('certificate', 'string')
            ->setAllowedValues('ctx_mode', ['TEST', 'PRODUCTION'])
            ->setAllowedTypes('directory', 'string')
            ->setAllowedValues('endpoint', $this->getEndPoints())
            ->setAllowedTypes('debug', 'bool')
            ->setNormalizer('directory', function (Options $options, $value) {
                return rtrim($value, DIRECTORY_SEPARATOR);
            });

        return $this->configResolver = $resolver;
    }

    /**
     * Returns request options resolver.
     *
     * @return OptionsResolver
     */
    private function getRequestOptionsResolver()
    {
        if (null !== $this->requestOptionsResolver) {
            return $this->requestOptionsResolver;
        }

        $resolver = new OptionsResolver();

        $resolver
            ->setDefaults([
                'vads_action_mode'              => 'INTERACTIVE',
                'vads_available_languages'      => null,
                'vads_capture_delay'            => null,
                'vads_card_info'                => null,
                'vads_card_options'             => null,
                'vads_card_number'              => null,
                'vads_contracts'                => function (Options $options) {
                    /* TODO
                    Obligatoire si le numéro de contrat commerçant à utiliser n’est pas celui configuré par défaut
                    sur la plateforme de paiement
                    */
                    return null;
                },
                'vads_contrib'                  => null,
                'vads_cust_address'             => null,
                'vads_cust_cell_phone'          => null,
                'vads_cust_city'                => null,
                'vads_cust_country'             => null,
                'vads_cust_email'               => function (Options $options) {
                    /* TODO
                    Obligatoire si souscription à l'envoi d'e-mail de confirmation de paiement au client
                    */
                    return null;
                },
                'vads_cust_id'                  => null,
                'vads_cust_name'                => null,
                'vads_cust_phone'               => null,
                'vads_cust_title'               => null,
                'vads_cust_zip'                 => null,
                'vads_cvv'                      => null,
                'vads_expiry_month'             => null,
                'vads_expiry_year'              => null,
                'vads_language'                 => null,
                'vads_order_id'                 => null, // [a-zA-Z0-9-]+
                'vads_order_info'               => null,
                'vads_order_info2'              => null,
                'vads_order_info3'              => null,
                'vads_page_action'              => 'PAYMENT',
                'vads_payment_cards'            => null, // Obligatoire si acquisition de la carte par commerçant
                'vads_payment_config'           => 'SINGLE',
                'vads_payment_src'              => null, // Obligatoire pour vente à distance
                'vads_redirect_error_message'   => null,
                'vads_redirect_error_timeout'   => null,
                'vads_redirect_success_message' => null,
                'vads_redirect_success_timeout' => null,
                'vads_return_get_params'        => null,
                'vads_return_mode'              => function (Options $options) {
                    /* TODO
                    Obligatoire si souhait du commerçant de recevoir la réponse à la demande sur l’URL internet
                    de retour boutique en formulaire GET ou POST (après clic internaute sur bouton retour
                    boutique).
                    Ce paramétrage n’impacte pas la transmission, ni les paramètres de transfert, de la réponse
                    de serveur à serveur (URL serveur commerçant).
                    */
                    return 'POST';
                },
                'vads_return_post_params'       => null,
                'vads_ship_to_city'             => null,
                'vads_ship_to_country'          => null,
                'vads_ship_to_name'             => null,
                'vads_ship_to_phone_num'        => null,
                'vads_ship_to_state'            => null,
                'vads_ship_to_street'           => null,
                'vads_ship_to_street2'          => null,
                'vads_ship_to_zip'              => null,
                'vads_shop_name'                => null,
                'vads_shop_url'                 => null,
                'vads_theme_config'             => null,
                'vads_threeds_cavv'             => null, // Obligatoire si 3DS à la charge du client
                'vads_threeds_cavvAlgorithm'    => null, // Obligatoire si 3DS à la charge du client
                'vads_threeds_eci'              => null, // Obligatoire si 3DS à la charge du client
                'vads_threeds_enrolled'         => null, // Obligatoire si 3DS à la charge du client
                'vads_threeds_mpi'              => null, // Obligatoire si 3DS à la charge du client
                'vads_threeds_status'           => null, // Obligatoire si 3DS à la charge du client
                'vads_threeds_xid'              => null, // Obligatoire si 3DS à la charge du client
                'vads_validation_mode'          => null,
                'vads_url_cancel'               => null,
                'vads_url_check'                => null,
                'vads_url_error'                => null,
                'vads_url_referral'             => null,
                'vads_url_refused'              => null,
                'vads_url_success'              => null,
                'vads_url_return'               => null, // Obligatoire si acquisition de la carte par commerçant
                'vads_user_info'                => null,
                'vads_version'                  => 'V2',
                'vads_sub_amount'               => null,
                'vads_sub_currency'             => null,
                'vads_sub_effect_date'          => null,
                'vads_sub_desc'                 => null,
            ])
            ->setRequired([
                'vads_amount',
                'vads_currency',
                'vads_payment_config',
                'vads_trans_date',
                'vads_trans_id',
                'vads_version',
            ])
            ->setAllowedValues('vads_action_mode', ['SILENT', 'INTERACTIVE'])
            ->setAllowedValues('vads_currency', $this->getCurrencyCodes())
            ->setAllowedValues('vads_language', $this->getLanguageCodes())
            ->setAllowedValues('vads_page_action', ['PAYMENT', 'REGISTER_PAY_SUBSCRIBE'])
            ->setAllowedValues('vads_payment_cards', $this->getCardsCodes())
            ->setAllowedValues('vads_payment_config', function ($value) {
                if ($value === 'SINGLE') {
                    return true;
                }

                // Ex: MULTI:first=5000;count=3;period=30
                if (preg_match('~^MULTI:first=\d+;count=\d+;period=\d+$~', $value)) {
                    return true;
                }

                // Ex: MULTI_EXT:20120601=5000;20120701=2500;20120808=2500
                if (preg_match('MULTI_EXT:\d+=\d+;\d+=\d+;\d+=\d+', $value)) {
                    return true;
                }

                return false;
            })
            ->setAllowedValues('vads_payment_src', [null, 'BO', 'MOTO', 'CC', 'OTHER'])
            ->setAllowedValues('vads_return_mode', [null, 'NONE', 'GET', 'POST'])
            ->setAllowedValues('vads_validation_mode', [null, '0', '1'])
            ->setAllowedValues('vads_version', 'V2');


        return $this->requestOptionsResolver = $resolver;
    }

    private function getCurrencyCodes()
    {
        return [
            '36', // Dollar australien
            '036', // Dollar australien
            '124', // Dollar canadien
            '156', // Yuan chinois
            '208', // Couronne danoise
            '392', // Yen japonais
            '578', // Couronne norvégienne
            '752', // Couronne suédoise
            '756', // Franc suisse
            '826', // Livre sterling
            '840', // Dollar américain
            '953', // Franc pacifique
            '978', // Euro
        ];
    }

    private function getLanguageCodes()
    {
        return [
            null,
            'de', // Allemand
            'en', // Anglais
            'zh', // Chinois
            'es', // Espagnol
            'fr', // Français
            'it', // Italien
            'jp', // Japonais
            'pt', // Portugais
            'nl', // Néelandais
        ];
    }

    private function getCardsCodes()
    {
        return [
            null,
            'AMEX',         // American Express
            'AURORE-MULTI', // Aurore
            'BUYSTER',      // Buyster
            'CB',           // CB
            'COFINOGA',     // Cofinoga
            'E-CARTEBLEUE', // E-Carte bleue
            'MASTERCARD',   // Eurocard / Mastercard
            'JCB',          // JCB
            'MAESTRO',      // Maestro
            'ONEY',         // Oney
            'ONEY_SANDBOX', // Oney (sandbox)
            'PAYPAL',       // Paypal
            'PAYPAL_SB',    // Paypal (sandbox)
            'PAYSAFECARD',  // Paysafe card
            'VISA',         // Visa
        ];
    }

    private function getEndPoints()
    {
        return [null, 'SYSTEMPAY'];
    }

    private function getUrl()
    {
        if ($this->config['endpoint'] === 'SYSTEMPAY') {
            return 'https://paiement.systempay.fr/vads-payment/';
        }

        return 'https://secure.payzen.eu/vads-payment/';
    }

    private function hash(string $content) {
        if ($this->config['endpoint'] === 'SYSTEMPAY') {
            return sha1($content);
        }

        return base64_encode(hash_hmac('sha256', $content, $this->config['certificate'], true));
    }
}