Crypto.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace App\Services;
  3. use App\Util;
  4. use http\Client\Curl\User;
  5. use function GuzzleHttp\Psr7\build_query;
  6. class Crypto
  7. {
  8. public $apiSecret;
  9. public $apiKey;
  10. public $config;
  11. public $api;
  12. public function __construct()
  13. {
  14. $payConfigService = new PayConfig();
  15. $this->config = $payConfigService->getConfig('Crypto');
  16. $this->apiKey = $this->config['apiKey'];
  17. $this->apiSecret = $this->config['apiSecret'];
  18. $this->api = $this->config['api'];
  19. }
  20. public function sign($method, $path, $body,$timestamp)
  21. {
  22. // 构造 payload 字符串
  23. $payload = $method . '|' . $path . '|' . $timestamp . '|' . json_encode($body);
  24. // 生成 HMAC-SHA256 签名
  25. $signature = hash_hmac('sha256', $payload, $this->apiSecret, true);
  26. // 返回 Base64 编码的签名
  27. return base64_encode($signature);
  28. }
  29. public function curlPost($path, $data)
  30. {
  31. $timestamp = time(); // time() 返回当前的 Unix 时间戳(秒)
  32. $sign = $this->sign('POST', $path, $data,$timestamp);
  33. // 定义请求的头部信息
  34. $headers = [
  35. 'X-API-KEY: '.$this->apiKey,
  36. 'X-SIGNATURE: '.$sign,
  37. 'TIMESTAMP: '.$timestamp,
  38. 'Content-Type: application/json',
  39. ];
  40. // 初始化 cURL
  41. $ch = curl_init();
  42. // 配置 cURL 选项
  43. curl_setopt($ch, CURLOPT_URL, $this->api.$path);
  44. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  45. curl_setopt($ch, CURLOPT_POST, true);
  46. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  47. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  48. // 执行请求并获取响应
  49. $response = curl_exec($ch);
  50. Util::WriteLog('Crypto_rs','Crypto支付结果'.$response);
  51. if ($response === false) {
  52. // Handle error
  53. echo 'cURL Error: ' . curl_error($ch);
  54. }else{
  55. $response = json_decode($response, true);
  56. }
  57. curl_close($ch);
  58. return $response;
  59. }
  60. }