API接口使用指南(进阶篇)

一、批量操作

批量生成短链接

$key = 'your_api_key';

$urls = [

    'https://example.com/page1',

    'https://example.com/page2',

    'https://example.com/page3'

];

$results = [];

foreach ($urls as $url) {

    $api_url = 'https://jili5.cn/api/shorturl.php';

    $data = [

    'key' => $key,

    'url' => $url

    ];

    $response = file_get_contents($api_url . '?' . http_get_contents($data));

    $result = json_decode($response, true);

    $results[] = $result;

    // 添加延迟,避免频率限制

    usleep(100000); // 0.1秒

}

print_r($results);

?>

异步批量处理

import requests

import asyncio

import aiohttp

async def create_shorturl(session, key, url):

    api_url = 'https://jili5.cn/api/shorturl.php'

    params = {'key': key, 'url': url}

    async with session.get(api_url, params=params) as response:

    return await response.json()

async def batch_create(key, urls):

    async with aiohttp.ClientSession() as session:

    tasks = [create_shorturl(session, key, url) for url in urls]

    return await asyncio.gather(*tasks)

使用

urls = ['https://example.com/1', 'https://example.com/2']

results = asyncio.run(batch_create('your_key', urls))

二、错误处理机制

重试机制

import requests

import time

def api_call_with_retry(url, params, max_retries=3):

    for i in range(max_retries):

    try:

    response = requests.get(url, params=params, timeout=10)

    result = response.json()

    if result['code'] == 200:

    return result

    elif result['code'] == 429: # 频率限制

    time.sleep(2 ** i) # 指数退避

    continue

    else:

    return result

    except Exception as e:

    if i == max_retries - 1:

    raise e

    time.sleep(1)

    return None

异常处理

try {

    $response = file_get_contents($api_url);

    if ($response === false) {

    throw new Exception('请求失败');

    }

    $result = json_decode($response, true);

    if (json_last_error() !== JSON_ERROR_NONE) {

    throw new Exception('JSON解析失败');

    }

    if ($result['code'] != 200) {

    throw new Exception($result['msg']);

    }

    // 处理成功结果

} catch (Exception $e) {

    // 记录错误日志

    error_log('API错误: ' . $e->getMessage());

    // 返回错误信息

    echo '操作失败: ' . $e->getMessage();

}

?>

三、性能优化

连接池

from requests.adapters import HTTPAdapter

from requests.packages.urllib3.util.retry import Retry

session = requests.Session()

配置重试策略

retry_strategy = Retry(

    total=3,

    backoff_factor=1,

    status_forcelist=[429, 500, 502, 503, 504]

)

adapter = HTTPAdapter(max_retries=retry_strategy, pool_connections=10, pool_maxsize=10)

session.mount("https://", adapter)

使用会话

response = session.get(api_url, params=params)

缓存机制

// 使用文件缓存

function get_cached_or_api($cache_key, $api_callback, $ttl = 3600) {

    $cache_file = 'cache/' . md5($cache_key) . '.json';

    // 检查缓存

    if (file_exists($cache_file) && (time() - filemtime($cache_file)) < $ttl) {

    return json_decode(file_get_contents($cache_file), true);

    }

    // 调用API

    $result = $api_callback();

    // 保存缓存

    if ($result['code'] == 200) {

    file_put_contents($cache_file, json_encode($result));

    }

    return $result;

}

?>

四、签名验证

生成签名

function generate_sign($params, $secret) {

    // 按key排序

    ksort($params);

    // 拼接字符串

    $string = '';

    foreach ($params as $key => $value) {

    $string .= $key . '=' . $value . '&';

    }

    $string .= 'secret=' . $secret;

    // MD5加密

    return md5($string);

}

// 使用

$params = [

    'key' => 'your_key',

    'url' => 'https://example.com',

    'timestamp' => time()

];

$params['sign'] = generate_sign($params, 'your_secret');

?>

五、Webhook接收

接收异步通知

// 接收Webhook

$json = file_get_contents('php://input');

$data = json_decode($json, true);

// 验证签名

$sign = $_SERVER['HTTP_X_SIGNATURE'] ?? '';

$expected_sign = hash_hmac('sha256', $json, 'your_secret');

if (!hash_equals($expected_sign, $sign)) {

    http_response_code(401);

    exit('Invalid signature');

}

// 处理通知

if ($data['event'] == 'order.completed') {

    // 处理订单完成

}

// 返回成功

echo json_encode(['code' => 200]);

?>

六、监控与日志

记录API调用

import logging

import time

logging.basicConfig(filename='api.log', level=logging.INFO)

def log_api_call(func):

    def wrapper(*args, **kwargs):

    start = time.time()

    try:

    result = func(*args, **kwargs)

    duration = time.time() - start

    logging.info(f'Success: {func.__name__}, Duration: {duration:.2f}s')

    return result

    except Exception as e:

    duration = time.time() - start

    logging.error(f'Failed: {func.__name__}, Error: {str(e)}, Duration: {duration:.2f}s')

    raise

    return wrapper

@log_api_call

def create_shorturl(url):

API调用逻辑

    pass

七、SDK封装

封装PHP SDK

class Jili5API {

    private $key;

    private $base_url = 'https://jili5.cn/api/';

    public function __construct($key) {

    $this->key = $key;

    }

    public function createShorturl($url) {

    return $this->request('shorturl.php', ['url' => $url]);

    }

    public function createFanghong($url) {

    return $this->request('fanghong.php', ['url' => $url]);

    }

    private function request($endpoint, $params) {

    $params['key'] = $this->key;

    $url = $this->base_url . $endpoint;

    $response = file_get_contents($url . '?' . http_build_query($params));

    return json_decode($response, true);

    }

}

// 使用

$api = new Jili5API('your_key');

$result = $api->createShorturl('https://example.com');

?>

---

下一篇:财务管理与充值提现