BaiduCpc.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace app\common\components;
  3. use Yii;
  4. /**
  5. * Class APIDemo API回传数据Demo
  6. */
  7. class BaiduCpc {
  8. const BAIDU_OCPC_URL = 'https://ocpc.baidu.com/ocpcapi/api/uploadConvertData';
  9. const RETRY_TIMES = 3;
  10. /**
  11. * @param $token
  12. * @param $conversionTypes
  13. * @return bool 发送成功返回true,失败返回false
  14. */
  15. public function sendConvertData($token, $conversionTypes) {
  16. $reqData = array('token' => $token, 'conversionTypes' => $conversionTypes);
  17. $reqData = json_encode($reqData);
  18. // 发送完整的请求数据
  19. // do some log
  20. //print_r('req data: ' . $reqData . "\n");
  21. // 向百度发送数据
  22. $ch = curl_init();
  23. curl_setopt($ch, CURLOPT_POST, 1);
  24. curl_setopt($ch, CURLOPT_URL, self::BAIDU_OCPC_URL);
  25. curl_setopt($ch, CURLOPT_POSTFIELDS, $reqData);
  26. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  27. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  28. 'Content-Type: application/json; charset=utf-8',
  29. 'Content-Length: ' . strlen($reqData)
  30. )
  31. );
  32. // 添加重试,重试次数为3
  33. for ($i = 0; $i < self::RETRY_TIMES; $i++) {
  34. $response = curl_exec($ch);
  35. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  36. if ($httpCode === 200) {
  37. // 打印返回结果
  38. // do some log
  39. //print_r('retry times: ' . $i . ' res: ' . $response . "\n");
  40. $res = json_decode($response, true);
  41. // status为4,代表服务端异常,可添加重试
  42. $status = $res['header']['status'];
  43. if ($status !== 4) {
  44. curl_close($ch);
  45. return $status === 0;
  46. }
  47. }
  48. }
  49. curl_close($ch);
  50. return false;
  51. }
  52. }