Request.php 1.9 KB
<?php

namespace Lackoxygen\MinPayment\Request;

use GuzzleHttp\RequestOptions;
use Illuminate\Support\Arr;
use Lackoxygen\MinPayment\Utils\Signature;
use ReflectionProperty;

class Request
{
    /**
     * @var string
     */
    protected $mchtId;

    /**
     * @var string
     */
    protected $service;

    /**
     * @var string
     */
    protected $ver;

    /**
     * @var string
     */
    protected $token;

    /**
     * @return string
     */
    public function getMethod(): string
    {
        return 'POST';
    }

    /**
     * @return string
     */
    public function getPath(): string
    {
        return 'Gateway';
    }

    /**
     * @return string
     */
    public function getOption(): string
    {
        return RequestOptions::JSON;
    }


    /**
     * @param array $config
     *
     * @return array
     */
    public function __invoke(array $config = []): array
    {

        $this->paddingHead($config);

        $body = $this->extract();

        $this->signature($body, Arr::get($config, 'secret'));

        return $body;
    }

    private function signature(&$body, string $secret)
    {
        $body['sign'] = Signature::make($body, $secret);
    }

    private function paddingHead(array $config)
    {
        $this->mchtId = Arr::get($config, 'merchant_id');
        $this->token  = Signature::encode(microtime(true) . uniqid(''));
        $this->ver    = Arr::get($config, 'version', 'V3.1');
    }

    /**
     * @return array
     */
    private function extract(): array
    {
        $propertiesArray = [];

        $ref = new \ReflectionClass($this);

        $properties = $ref->getProperties(ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED);

        foreach ($properties as $property) {
            $property->setAccessible(true);

            $propertiesArray[$property->getName()] = $property->getValue($this);
        }

        return $propertiesArray;
    }
}