<?php
/**
 * 文件名称（处理京东数据）
 * 文件简单描述（处理京东数据）
 * @author DouBin
 * @Date: 2025/9/18
 * @Time: 15:59
 * @Email: db@sudianwang.com
 * @version 1.0
 * @copyright BlueCity
 */

namespace App\Services;

use BlueCity\Core\Service\Service;

class JdDataService extends Service{

    /**|---------------------------------------------------------------------------------
     * @name 生成签名
     * @param string $params 参数
     * @param string $appsecret appsecret
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2025/9/18 15:33
     * |---------------------------------------------------------------------------------
     */
    public static function generateSign($params,$appsecret) {
        if ($params != null) { // 所有请求参数按照字母先后顺序排序
            ksort($params);
            // 定义字符串开始 结尾所包括的字符串
            $stringToBeSigned = $appsecret;
            // 把所有参数名和参数值串在一起
            foreach ($params as $k => $v) {
                $stringToBeSigned .= "$k$v";
            }
            unset($k, $v);

            // 把venderKey加在字符串的两端
            $stringToBeSigned .= $appsecret;
        } else {
            // 定义字符串开始 结尾所包括的字符串
            $stringToBeSigned = $appsecret;
            // 把venderKey加在字符串的两端
            $stringToBeSigned .= $appsecret;
        }
        // 使用MD5进行加密，再转化成大写

        return strtoupper(md5($stringToBeSigned));
    }

    /**|---------------------------------------------------------------------------------
     * @name 解密京东秒送加密信息
     * @param string $encrypted 加密信息
     * @param string $appsecret appsecret
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2025/9/18 16:03
     * |---------------------------------------------------------------------------------
    */
    public static function decryptAES ( $encrypted,$appsecret ){
        $k =  substr($appsecret, 0, 16);
        $v = substr($appsecret, -16);
        $encrypted = base64_decode($encrypted);
        $decrypted = openssl_decrypt(
            $encrypted,
            'AES-128-CBC',
            $k,
            OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING,
            $v
        );
        $decrypted = trim($decrypted);
        return $decrypted;
    }
}
