PayUtils.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace common\pay\kexing;
  3. use Yii;
  4. use yii\helpers\VarDumper;
  5. class PayUtils
  6. {
  7. /**
  8. * @param array $params
  9. * @param string $priCert
  10. * @return string
  11. */
  12. public static function makeSign($params, $priCert)
  13. {
  14. ksort($params);
  15. $temp = '';
  16. foreach($params as $key=>$value)
  17. {
  18. $temp = $temp . $key . '=' . $value . '&';
  19. }
  20. $temp = substr($temp, 0, strlen($temp) -1 );
  21. $priKey = openssl_get_privatekey(file_get_contents($priCert));
  22. openssl_sign($temp, $sign, $priKey, OPENSSL_ALGO_SHA1);
  23. $sign = base64_encode($sign);
  24. return $sign;
  25. }
  26. /**
  27. * @param array $data
  28. * @param $pubCert
  29. * @return bool|int
  30. */
  31. public static function verify($data, $pubCert)
  32. {
  33. // 签名
  34. if (!isset($data['signature']) || trim($data['signature']) === '') {
  35. return false;
  36. }
  37. $sign = $data['signature'];
  38. unset($data['signature']);
  39. ksort($data);
  40. $temp = '';
  41. foreach($data as $key=>$value)
  42. {
  43. $temp = $temp . $key . '=' . $value . '&';
  44. }
  45. $temp = substr($temp, 0, strlen($temp) -1 );
  46. $pubKey = openssl_get_publickey(file_get_contents($pubCert));
  47. return openssl_verify($temp, base64_decode($sign), $pubKey, OPENSSL_ALGO_SHA1);
  48. }
  49. /**
  50. * 发送post请求
  51. * @param string $url 请求地址
  52. * @param array $post_data post键值对数据
  53. * @return string
  54. */
  55. public static function sendPost($url, $post_data) {
  56. $postdata = http_build_query($post_data);
  57. $options = array(
  58. 'http' => array(
  59. 'method' => 'POST',
  60. 'header' => 'Content-type:application/x-www-form-urlencoded',
  61. 'content' => $postdata,
  62. 'timeout' => 15 * 60 // 超时时间(单位:s)
  63. )
  64. );
  65. $context = stream_context_create($options);
  66. $result = file_get_contents($url, false, $context);
  67. return $result;
  68. }
  69. }