123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- <?php
- namespace daorui;
- /**
- * @title:三方接口基础类
- * @user: zwq
- * @date: 2025-01-09 14:58
- */
- class DaoRuiBase
- {
- /**
- * 构造方法
- */
- public function __construct()
- {
- }
- /**
- * @title :[获取缓存]
- * @param string $field
- * @return array|object|json|{*}
- * @Author : byl
- * @Date :2025/1/9 9:13
- */
- protected function getCache(string $field)
- {
- $cacheData = cache($field);
- if ($cacheData) {
- // 如果为字符串则处理为数组
- if (is_string($cacheData)) {
- $cacheData = json_decode($cacheData, true);
- }
- return $cacheData;
- }
- return [];
- }
- /**
- * @title :[设置缓存]
- * @param $data 缓存数据
- * @param $field 缓存key
- * @param $endTime 过期时间
- * @return json|{*}
- * @Author : byl
- * @Date :2025/1/9 9:04
- */
- protected function setCache(array $data, string $field, $endTime)
- {
- cache($field, $data, ['expire' => $endTime]);
- }
- /**
- * @title :[curl发送请求]
- * @param string $url 请求地址
- * @param array $data 请求参数
- * @param array $header 请求头
- * @param string $method 请求方式
- * @return bool|string
- * @return json|{*}
- * @Author : byl
- * @Date :2025/1/8 20:01
- * @throws \Exception
- */
- public function SendCurl(string $url, array $data = [], array $header = [], string $method = 'POST')
- {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
- // 根据请求方法设置相应的curl选项
- switch ($method) {
- case 'GET':
- if (!empty($data)) {
- $parsed_url = parse_url($url);
- if(isset($parsed_url['query'])){
- $url .= '&' . http_build_query($data);
- }else{
- $url .= '?' . http_build_query($data);
- }
- }
- break;
- case 'POST':
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
- break;
- default:
- throw new \Exception("不支持的请求方法");
- }
- // 设置请求头
- $headerArr = [];
- foreach ($header as $key => $value) {
- $headerArr[] = $key . ': ' . $value;
- }
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr);
- // 设置请求的URL
- curl_setopt($ch, CURLOPT_URL, $url);
- // 执行curl请求并返回结果
- $response = curl_exec($ch);
- // 检查curl请求是否出错
- if (curl_errno($ch)) {
- throw new \Exception(curl_error($ch));
- }
- curl_close($ch);
- if (is_string($response)) {
- $response = json_decode($response, true);
- }
- Wlog('BaseDaoRui/SendCurl', [
- 'url' => $url,
- 'data' => $data,
- 'header' => $header,
- 'method' => $method,
- 'response' => $response,
- ]);
- return $response;
- }
- }
|