PayHttpClient.class.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. /**
  3. * http、https通信类
  4. * ============================================================================
  5. * api说明:
  6. * setReqContent($reqContent),设置请求内容,无论post和get,都用get方式提供
  7. * getResContent(), 获取应答内容
  8. * setMethod($method),设置请求方法,post或者get
  9. * getErrInfo(),获取错误信息
  10. * setCertInfo($certFile, $certPasswd, $certType="PEM"),设置证书,双向https时需要使用
  11. * setCaInfo($caFile), 设置CA,格式未pem,不设置则不检查
  12. * setTimeOut($timeOut), 设置超时时间,单位秒
  13. * getResponseCode(), 取返回的http状态码
  14. * call(),真正调用接口
  15. * ============================================================================
  16. */
  17. class PayHttpClient {
  18. // 请求内容,无论post和get,都用get方式提供
  19. var $reqContent = array();
  20. // 应答内容
  21. var $resContent;
  22. // 错误信息
  23. var $errInfo;
  24. // 超时时间
  25. var $timeOut;
  26. // http状态码
  27. var $responseCode;
  28. function __construct() {
  29. $this->PayHttpClient();
  30. }
  31. function PayHttpClient() {
  32. $this->reqContent = array();
  33. $this->resContent = "";
  34. $this->errInfo = "";
  35. $this->timeOut = 120;
  36. $this->responseCode = 0;
  37. }
  38. // 设置请求内容
  39. function setReqContent($url, $data) {
  40. $this->reqContent['url'] = $url;
  41. $this->reqContent['data'] = $data;
  42. }
  43. // 获取结果内容
  44. function getResContent() {
  45. return $this->resContent;
  46. }
  47. // 获取错误信息
  48. function getErrInfo() {
  49. return $this->errInfo;
  50. }
  51. // 设置超时时间,单位秒
  52. function setTimeOut($timeOut) {
  53. $this->timeOut = $timeOut;
  54. }
  55. // 执行http调用
  56. function call() {
  57. // 启动一个CURL会话
  58. $ch = curl_init();
  59. // 设置curl允许执行的最长秒数
  60. curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeOut);
  61. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  62. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  63. // 获取的信息以文件流的形式返回,而不是直接输出。
  64. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  65. // 发送一个常规的POST请求。
  66. curl_setopt($ch, CURLOPT_POST, 1);
  67. curl_setopt($ch, CURLOPT_URL, $this->reqContent['url']);
  68. // 要传送的所有数据
  69. curl_setopt($ch, CURLOPT_POSTFIELDS, $this->reqContent['data']);
  70. // 执行操作
  71. $res = curl_exec($ch);
  72. $this->responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  73. if ($res == null) {
  74. $this->errInfo = "call http err :".curl_errno($ch)." - ".curl_error($ch);
  75. curl_close($ch);
  76. return false;
  77. } else if ($this->responseCode != "200") {
  78. $this->errInfo = "call http err httpcode=".$this->responseCode;
  79. curl_close($ch);
  80. return false;
  81. }
  82. curl_close($ch);
  83. $this->resContent = $res;
  84. return true;
  85. }
  86. function getResponseCode() {
  87. return $this->responseCode;
  88. }
  89. }
  90. ?>