SDK 把 Bearer 鉴权、JSON 序列化、错误处理封装成一次 call 调用,业务代码只需传「接口标识 + 业务参数」。每种语言给出两组代码块:① SDK 源码(保存为文件,一次引入长期复用)与 ② 调用代码。除 Python 需 pip install requests 外,其余均用语言标准库,无第三方依赖。示例以 ipquery 接口演示。
"""聚合API平台轻量 SDK(Python 3.6+,pip install requests)"""
import requests
class ApiError(Exception):
"""业务错误:code 非 0"""
def __init__(self, code, desc):
self.code = code
self.desc = desc
super().__init__(f"{code} {desc}")
class WcApi:
def __init__(self, key, host="https://api.phpwc.com"):
self.host = host.rstrip("/")
self.session = requests.Session()
self.session.headers.update({
"Authorization": f"Bearer {key}", # 凭证只走这个头
"Content-Type": "application/json",
})
def call(self, jk, params=None):
"""调用接口:jk=接口标识,params=业务参数字典;成功返回 data,失败抛 ApiError"""
resp = self.session.post(f"{self.host}/api/{jk}", json=params or {}, timeout=10)
result = resp.json()
if result.get("code") != 0:
raise ApiError(result.get("code"), result.get("desc"))
return result["data"]
import time
from wcapi import WcApi, ApiError
api = WcApi("你的key") # 主key 或副key,用户中心 → API设置
try:
data = api.call("ipquery", {"ip": "8.8.8.8"})
print(data)
except ApiError as e:
print(f"调用失败:{e.code} {e.desc}")
# ========== 异步任务接口:提交后轮询(轮询免费) ==========
# task = api.call("doctranslate", {...})
# while True:
# r = api.call("taskresult", {"task_id": task["task_id"]})
# if r["output_status"] in ("finish", "fail"): # 其余取值:not / processing
# break
# time.sleep(5)
package wcapi
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
type Client struct {
Host string
Key string
http *http.Client
}
func New(key string) *Client {
return &Client{
Host: "https://api.phpwc.com",
Key: key, // 主key 或副key
http: &http.Client{Timeout: 10 * time.Second},
}
}
// Call 调用接口:jk=接口标识,params=业务参数;成功返回 data,失败返回 error
func (c *Client) Call(jk string, params map[string]interface{}) (map[string]interface{}, error) {
body, _ := json.Marshal(params)
req, err := http.NewRequest("POST", c.Host+"/api/"+jk, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+c.Key) // 凭证只走这个头
req.Header.Set("Content-Type", "application/json")
resp, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
raw, _ := io.ReadAll(resp.Body)
var result struct {
Code int `json:"code"`
Desc string `json:"desc"`
Data map[string]interface{} `json:"data"`
}
if err := json.Unmarshal(raw, &result); err != nil {
return nil, err
}
if result.Code != 0 {
return nil, fmt.Errorf("%d %s", result.Code, result.Desc)
}
return result.Data, nil
}
package main
import (
"fmt"
"你的模块名/wcapi" // 按 go.mod 的 module 名调整
)
func main() {
api := wcapi.New("你的key") // 主key 或副key,用户中心 → API设置
data, err := api.Call("ipquery", map[string]interface{}{"ip": "8.8.8.8"})
if err != nil {
fmt.Println("调用失败:", err)
return
}
fmt.Println(data)
// 异步任务接口:提交后轮询(轮询免费)
// task, _ := api.Call("doctranslate", map[string]interface{}{...})
// for {
// r, _ := api.Call("taskresult", map[string]interface{}{"task_id": task["task_id"]})
// if r["output_status"] == "finish" || r["output_status"] == "fail" { break }
// time.Sleep(5 * time.Second)
// }
}
<?php
/**
* 聚合API平台轻量 SDK(PHP 7.0+,需 curl 扩展)
*/
class WcApi
{
private $host;
private $key;
public function __construct($key, $host = 'https://api.phpwc.com')
{
$this->host = rtrim($host, '/');
$this->key = $key; // 主key 或副key
}
/**
* 调用接口:$jk=接口标识,$params=业务参数数组
* 成功返回 data 数组;失败抛 RuntimeException(含错误码与描述)
*/
public function call($jk, array $params = [])
{
$ch = curl_init($this->host . '/api/' . $jk);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $this->key, // 凭证只走这个头
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode($params, JSON_UNESCAPED_UNICODE),
]);
$resp = curl_exec($ch);
if ($resp === false) {
$err = curl_error($ch);
curl_close($ch);
throw new RuntimeException('网络错误:' . $err);
}
curl_close($ch);
$result = json_decode($resp, true);
if ((int) $result['code'] !== 0) {
throw new RuntimeException($result['code'] . ' ' . $result['desc']);
}
return $result['data'];
}
}
<?php
require 'WcApi.php';
$api = new WcApi('你的key'); // 主key 或副key,用户中心 → API设置
try {
$data = $api->call('ipquery', ['ip' => '8.8.8.8']);
print_r($data);
} catch (RuntimeException $e) {
echo '调用失败:' . $e->getMessage() . "\n";
}
// ========== 异步任务接口:提交后轮询(轮询免费) ==========
// $task = $api->call('doctranslate', [...]);
// while (true) {
// $r = $api->call('taskresult', ['task_id' => $task['task_id']]);
// if (in_array($r['output_status'], ['finish', 'fail'])) break;
// sleep(5);
// }
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
/**
* 聚合API平台轻量 SDK(JDK 8+,零第三方依赖)
* call 返回原始 JSON 字符串,可用 Jackson / Gson 解析
*/
public class WcApi {
private final String host;
private final String key;
public WcApi(String key) {
this("https://api.phpwc.com", key);
}
public WcApi(String host, String key) {
this.host = host;
this.key = key; // 主key 或副key
}
/** 调用接口:jk=接口标识,jsonBody=业务参数 JSON 字符串 */
public String call(String jk, String jsonBody) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(host + "/api/" + jk).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setRequestProperty("Authorization", "Bearer " + key); // 凭证只走这个头
conn.setRequestProperty("Content-Type", "application/json");
conn.getOutputStream().write(jsonBody.getBytes(StandardCharsets.UTF_8));
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) sb.append(line);
return sb.toString();
}
}
public class Demo {
public static void main(String[] args) throws Exception {
WcApi api = new WcApi("你的key"); // 主key 或副key,用户中心 → API设置
String json = api.call("ipquery", "{\"ip\":\"8.8.8.8\"}");
System.out.println(json); // {"code":0,"desc":"...","data":{...}}
// 用 Jackson / Gson 解析后判断 code==0 取 data;
// 异步任务接口提交后,同样用 api.call("taskresult", ...) 每 5-10 秒轮询(轮询免费)
}
}
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
/// 聚合API平台轻量 SDK(.NET Core 3.0+ / .NET 5+)
public class WcApi
{
private readonly HttpClient _client = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
private readonly string _host;
public WcApi(string key, string host = "https://api.phpwc.com")
{
_host = host.TrimEnd('/');
_client.DefaultRequestHeaders.Add("Authorization", $"Bearer {key}"); // 凭证只走这个头
}
/// 调用接口:jk=接口标识,jsonBody=业务参数 JSON;返回原始 JSON 字符串
public async Task CallAsync(string jk, string jsonBody)
{
var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
var resp = await _client.PostAsync($"{_host}/api/{jk}", content);
return await resp.Content.ReadAsStringAsync();
}
}
using System;
using System.Threading.Tasks;
class Demo
{
static async Task Main()
{
var api = new WcApi("你的key"); // 主key 或副key,用户中心 → API设置
var json = await api.CallAsync("ipquery", "{\"ip\":\"8.8.8.8\"}");
Console.WriteLine(json); // 用 System.Text.Json / Newtonsoft 解析后判断 code==0 取 data
// 异步任务接口提交后,同样用 CallAsync("taskresult", ...) 每 5-10 秒轮询(轮询免费)
}
}
#import <Foundation/Foundation.h>
// ===== WcApi.h =====
@interface WcApi : NSObject
- (instancetype)initWithKey:(NSString *)key;
/// 调用接口:jk=接口标识,params=业务参数;返回完整响应字典(含 code/desc/data)
- (NSDictionary *)call:(NSString *)jk params:(NSDictionary *)params error:(NSError **)error;
@end
// ===== WcApi.m =====
@implementation WcApi {
NSString *_host;
NSString *_key;
}
- (instancetype)initWithKey:(NSString *)key {
if (self = [super init]) {
_host = @"https://api.phpwc.com";
_key = key; // 主key 或副key
}
return self;
}
- (NSDictionary *)call:(NSString *)jk params:(NSDictionary *)params error:(NSError **)error {
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:[NSString stringWithFormat:@"%@/api/%@", _host, jk]]];
[req setHTTPMethod:@"POST"];
[req setValue:[NSString stringWithFormat:@"Bearer %@", _key]
forHTTPHeaderField:@"Authorization"]; // 凭证只走这个头
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setHTTPBody:[NSJSONSerialization dataWithJSONObject:params options:0 error:nil]];
NSURLResponse *resp = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:&resp error:error];
if (!data) return nil;
return [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
}
@end
WcApi *api = [[WcApi alloc] initWithKey:@"你的key"]; // 主key 或副key,用户中心 → API设置
NSError *err = nil;
NSDictionary *result = [api call:@"ipquery" params:@{@"ip": @"8.8.8.8"} error:&err];
if (err) {
NSLog(@"网络错误:%@", err);
} else if ([result[@"code"] integerValue] == 0) {
NSLog(@"%@", result[@"data"]);
} else {
NSLog(@"调用失败:%@ %@", result[@"code"], result[@"desc"]);
}
// 异步任务接口提交后,同样用 call:@"taskresult" 每 5-10 秒轮询(轮询免费)
call 方法通用于全部接口:换接口只需改「接口标识 + 业务参数」,参数说明见 API市场 各接口详情页。task_id,需再调 taskresult 每 5-10 秒轮询至 finish/fail;轮询免费,不要把提交响应当最终结果。