AdaRequests.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace AdaPay\utils;
  3. use AdaPay\AdaPay;
  4. use think\facade\Db;
  5. class AdaRequests {
  6. public $postCharset = "utf-8";
  7. public function curl_request($url, $postFields = null, $headers=null, $is_json=false) {
  8. AdaPay::writeLog("curl方法参数:". json_encode(func_get_args(), JSON_UNESCAPED_UNICODE), "INFO");
  9. Db::name("log")->insert(array('data'=>'【发送的参数】'.json_encode($postFields),));//日志记录
  10. Db::name("log")->insert(array('data'=>'【URL:】'.$url,));//日志记录
  11. $ch = curl_init();
  12. curl_setopt($ch, CURLOPT_URL, $url);
  13. curl_setopt($ch, CURLOPT_FAILONERROR, false);
  14. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  15. curl_setopt($ch, CURLOPT_HEADER, 0);
  16. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  17. if (is_array($postFields) && 0 < count($postFields)) {
  18. curl_setopt($ch, CURLOPT_POST, true);
  19. if ($is_json) {
  20. $json_data = json_encode($postFields);
  21. AdaPay::writeLog("post-json请求参数:". json_encode($postFields, JSON_UNESCAPED_UNICODE), "INFO");
  22. array_push($headers, "Content-Length:". strlen($json_data));
  23. curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
  24. }else{
  25. AdaPay::writeLog("post-form请求参数:". json_encode($postFields, JSON_UNESCAPED_UNICODE), "INFO");
  26. curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
  27. }
  28. }
  29. if (empty($headers)){
  30. $headers = array('Content-type: application/x-www-form-urlencoded');
  31. }
  32. AdaPay::writeLog("curl请求头:". json_encode($headers, JSON_UNESCAPED_UNICODE), "INFO");
  33. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  34. $response = curl_exec($ch);
  35. $statuCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
  36. if (curl_errno($ch)) {
  37. AdaPay::writeLog(curl_error($ch), "ERROR");
  38. }
  39. curl_close($ch);
  40. AdaPay::writeLog("curl返回参数:". $statuCode. json_encode($response, JSON_UNESCAPED_UNICODE), "INFO");
  41. Db::name("log")->insert(array('data'=>'【请求结果】'.json_encode($response),));//日志记录
  42. return array($statuCode, $response);
  43. }
  44. function characet($data, $targetCharset) {
  45. if (!empty($data)) {
  46. $fileType = $this->postCharset;
  47. if (strcasecmp($fileType, $targetCharset) != 0) {
  48. $data = mb_convert_encoding($data, $targetCharset, $fileType);
  49. }
  50. }
  51. return $data;
  52. }
  53. }