Signature.php 1.9 KB
<?php

namespace Lackoxygen\TiktokShop\Util;

use Lackoxygen\TiktokShop\Attribute\Config\Config;

class Signature extends Config
{
    /**
     * @var string
     */
    private string $method;

    /**
     * @var string
     */
    private string $timestamp;

    /**
     * @var string
     */
    private string $paramJson;

    /**
     * @param mixed $method
     */
    public function setMethod($method): Signature
    {
        $this->method = $method;
        return $this;
    }

    /**
     * @param mixed $timestamp
     */
    public function setTimestamp($timestamp): Signature
    {
        $this->timestamp = $timestamp;
        return $this;
    }


    /**
     * @param mixed $paramJson
     */
    public function setParamJson($paramJson): Signature
    {
        $this->paramJson = $paramJson;
        return $this;
    }

    /**
     * @return string
     */
    public function generate()
    {
        $paramPattern = 'app_key' . $this->config->getAppKey(
            ) . 'method' . $this->method . 'param_json' . $this->paramJson .
            'timestamp' . $this->timestamp . 'v' . $this->config->getVersion();

        $body = $this->config->getAppSecret() . $paramPattern . $this->config->getAppSecret();

        switch ($this->config->getSignMethod()) {
            case 'hmac-sha256':
            case 'sha256':
                return $this->sha256($body);
            case 'md5':
                return $this->md5($body);
            default:
                return '';
        }
    }

    /**
     * @param string $body
     * @return false|string
     */
    protected function sha256(string $body): string
    {
        return (string)\hash_hmac("sha256", $body, $this->config->getAppSecret());
    }

    /**
     * @param string $body
     * @return string
     */
    protected function md5(string $body): string
    {
        return \md5($body . $this->config->getAppSecret());
    }
}