<?php
namespace common\pay\balpal;

class PayUtils
{
    /**
     * @var array
     */
    public static $hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];

    /**
     * @param array $data
     * @param string $secretKey
     * @return string
     */
    public static function makeSign($data, $secretKey)
    {
        ksort($data);
        $str = '';
        foreach ((array)$data as $key => $value) {
            if ($key == 'signData' || $key == 'signType') {
                continue;
            }
            $value = strval($value);
            if ($value === '') {
                continue;
            }
            $str .= "{$key}={$value}&";
        }
        $str = rtrim($str, '&');
        return self::strToHex(hash_hmac('sha1', $str, $secretKey, true));
    }

    /**
     * @param array $data
     * @param string $secretKey
     * @return bool
     */
    public static function checkSign($data, $secretKey)
    {
        $sign = isset($data['signData']) ? $data['signData'] : '';
        if ($sign == '') {
            return false;
        }
        return self::makeSign($data, $secretKey) == $sign;
    }

    /**
     * @param string $str
     * @return string
     */
    public static function strToHex($str)
    {
        $hexStr = '';
        for ($i = 0, $len = strlen($str); $i < $len; $i++) {
            $ascii = ord($str[$i]); // 0 - 255
            $hexStr .= self::$hex[$ascii >> 4 & 0x0f]; // 高4位
            $hexStr .= self::$hex[$ascii & 0x0f]; // 低4位
        }
        return $hexStr;
    }
}