<?php


namespace App\Services;


use App\Util;
use http\Client\Curl\User;
use function GuzzleHttp\Psr7\build_query;

class Crypto
{


    public $apiSecret;
    public $apiKey;

    public $config;

    public $api;
    public function __construct()
    {
        $payConfigService = new PayConfig();
        $this->config = $payConfigService->getConfig('Crypto');

        $this->apiKey = $this->config['apiKey'];
        $this->apiSecret = $this->config['apiSecret'];
        $this->api = $this->config['api'];

    }
    public function sign($method, $path, $body,$timestamp)
    {


        // 构造 payload 字符串
        $payload = $method . '|' . $path . '|' . $timestamp . '|' . json_encode($body);

        // 生成 HMAC-SHA256 签名
        $signature = hash_hmac('sha256', $payload, $this->apiSecret, true);

        // 返回 Base64 编码的签名
        return base64_encode($signature);
    }

    public function curlPost($path, $data)
    {
        $timestamp = time(); // time() 返回当前的 Unix 时间戳（秒）
        $sign = $this->sign('POST', $path, $data,$timestamp);

        // 定义请求的头部信息
        $headers = [
            'X-API-KEY: '.$this->apiKey,
            'X-SIGNATURE: '.$sign,
            'TIMESTAMP: '.$timestamp,
            'Content-Type: application/json',
        ];

        // 初始化 cURL
        $ch = curl_init();

// 配置 cURL 选项
        curl_setopt($ch, CURLOPT_URL, $this->api.$path);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

// 执行请求并获取响应
        $response = curl_exec($ch);

        Util::WriteLog('Crypto_rs','Crypto支付结果'.$response);

        if ($response === false) {
            // Handle error
            echo 'cURL Error: ' . curl_error($ch);
        }else{
            $response = json_decode($response, true);
        }
        curl_close($ch);
        return $response;
    }



}

