Verify.php 2.2 KB
<?php

namespace Lackoxygen\TiktokShop\Support;

use Illuminate\Support\Arr;
use Lackoxygen\TiktokShop\Application;
use Lackoxygen\TiktokShop\Attribute\Config\Config;
use Lackoxygen\TiktokShop\Attribute\Config\Option;
use Lackoxygen\TiktokShop\ServiceProvider;
use Illuminate\Http\Request;

class Verify extends Config
{
    /**
     * @var Signature
     */
    protected Signature $signature;

    /**
     * @param Option $option
     */
    public function __construct(Option $option)
    {
        parent::__construct($option);

        $this->signature = new Signature($option);
    }

    /**
     * @param string $sign
     * @param string $body
     * @return bool
     */
    public function md5(string $sign, string $body): bool
    {
        $md5 = $this->signature->md5(
            $this->config->getAppKey() .
            $body .
            $this->config->getAppSecret()
        );
        return $md5 === $sign;
    }

    /**
     * @param string $sign
     * @param string $body
     * @return bool
     */
    public function sha256(string $sign, string $body): bool
    {
        $sha256 = $this->signature->sha256(
            $body
        );

        return $sha256 === $sign;
    }

    /**
     * @param Request $request
     * @return bool|void
     */
    public function through(Request $request)
    {
        $signMethod = $request->getHeaderLine('sign-method');

        $eventSign = $request->getHeaderLine('event-sign');

        $appId = $request->getHeaderLine('app-id');

        $configs = \config(ServiceProvider::$name);

        $appName = null;

        foreach ($configs as $name => $config) {
            if (Arr::get($config, 'app_key') === $appId) {
                $appName = $name;
                break;
            }
        }

        if (!$appName) {
            throw new \InvalidArgumentException('Unknown application information');
        }

        $config = Arr::get($configs, $appName);

        $this->config = Application::newConfigFormArray($config);

        switch ($signMethod) {
            case 'hmac-sha256':
                return $this->sha256($eventSign, $request->getBody());
            case 'md5':
                return $this->md5($eventSign, $request->getBody());
        }
    }
}