WiwiPay.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace App\Services;
  3. use App\Util;
  4. class WiwiPay
  5. {
  6. public $config;
  7. public $key;
  8. public $mchNo;
  9. public $apiUrl;
  10. public function __construct()
  11. {
  12. $payConfigService = new PayConfig();
  13. $this->config = $payConfigService->getConfig('WiwiPay');
  14. $this->key = $this->config['key'] ?? '';
  15. $this->mchNo = $this->config['mchNo'] ?? '';
  16. $this->apiUrl = $this->config['apiUrl'];
  17. }
  18. /**
  19. * 签名
  20. */
  21. public function sign(array $params): array
  22. {
  23. return PayUtils::sign($params, $this->key);
  24. }
  25. /**
  26. * 验签
  27. */
  28. public function verifySign(array $params): bool
  29. {
  30. return PayUtils::verifySign($params, $this->key);
  31. }
  32. /**
  33. * 生成随机字符串
  34. */
  35. public function getNonceStr($length = 16): string
  36. {
  37. $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
  38. $str = "";
  39. for ($i = 0; $i < $length; $i++) {
  40. $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  41. }
  42. return $str;
  43. }
  44. /**
  45. * POST请求
  46. */
  47. public function curlPost($url, $payload)
  48. {
  49. $timeout = 20;
  50. $data = json_encode($payload, JSON_UNESCAPED_UNICODE);
  51. $headers = [
  52. 'Content-Type: application/json',
  53. ];
  54. $ch = curl_init();
  55. curl_setopt($ch, CURLOPT_URL, $url);
  56. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  57. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  58. curl_setopt($ch, CURLOPT_POST, 1);
  59. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  60. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  61. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  62. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  63. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  64. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  65. $result = curl_exec($ch);
  66. if (curl_errno($ch)) {
  67. $error = curl_error($ch);
  68. Util::WriteLog('WiwiPay_error', 'CURL Error: ' . $error);
  69. curl_close($ch);
  70. return false;
  71. }
  72. if (strstr($result, 'code') || $httpCode != 200) {
  73. // Util::WriteLog('WiwiPay_error', 'error_state_' . $httpCode . "|" . $result);
  74. }
  75. curl_close($ch);
  76. return $result;
  77. }
  78. }