CtuClient.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: dingxiang-inc
  5. * Date: 2017/8/19
  6. * Time: 下午1:29
  7. */
  8. include_once __DIR__ . "/model/CtuRequest.php";
  9. include_once __DIR__ . "/model/CtuResponse.php";
  10. include_once __DIR__ . "/util/SignUtil.php";
  11. class CtuClient
  12. {
  13. public $url; // 风险防控服务URL
  14. public $appId; // 颁发的公钥,可公开
  15. public $appSecret; // 颁发的秘钥,严禁公开,请保管好,千万不要泄露!
  16. public $connectTimeout = 3000;
  17. public $connectionRequestTimeout = 2000;
  18. public $socketTimeout = 5000;
  19. const UTF8_ENCODE = "UTF-8";
  20. const VERSION = 1; //client版本号 从1开始
  21. /**
  22. * CtuClient constructor.
  23. * @param $url
  24. * @param $appId
  25. * @param $appSecret
  26. */
  27. public function __construct($url, $appId, $appSecret)
  28. {
  29. $this->url = $url;
  30. $this->appId = $appId;
  31. $this->appSecret = $appSecret;
  32. }
  33. /**
  34. * @param $ctuRequest
  35. */
  36. public function checkRisk($ctuRequest, $timeout)
  37. {
  38. // 计算签名
  39. $sign = SignUtil::sign($this->appSecret, $ctuRequest);
  40. // 拼接请求URL
  41. $requestUrl = $this->url . "?appKey=" . $this->appId . "&sign=" . $sign . "&version=" . CtuClient::VERSION;
  42. $reqJsonString = json_encode($ctuRequest, JSON_UNESCAPED_UNICODE);
  43. $data = base64_encode($reqJsonString);
  44. return $this->do_post_request($requestUrl, $data, $timeout);
  45. }
  46. public function do_post_request($url, $data, $timeout = 2)
  47. {
  48. $ctuResponse = new CtuResponse("");
  49. $params = array('http' => array(
  50. 'method' => 'POST',
  51. 'content' => $data,
  52. 'header' => 'Content-type:text/html',
  53. 'timeout' => $timeout
  54. ));
  55. $ctx = stream_context_create($params);
  56. $fp = @fopen($url, 'rb', false, $ctx);
  57. if (!$fp) {
  58. $ctuResponse->result = array('riskLevel' => 'ACCEPT', 'msg' => 'server connect failed!');
  59. $this->close($fp);
  60. return json_encode($ctuResponse, JSON_FORCE_OBJECT);
  61. }
  62. $response = @stream_get_contents($fp);
  63. if ($response === false) {
  64. $ctuResponse->result = array('riskLevel' => 'ACCEPT', 'msg' => 'get response failed!');
  65. $this->close($fp);
  66. return json_encode($ctuResponse, JSON_FORCE_OBJECT);
  67. }
  68. $this->close($fp);
  69. return $response;
  70. }
  71. public function close($fp)
  72. {
  73. try {
  74. if ($fp != null) {
  75. fclose($fp);
  76. }
  77. } catch (Exception $e) {
  78. echo "close error:" . $e->getMessage();
  79. }
  80. }
  81. }