快速入门
Quick Start
只需几分钟,掌握 SmartCheapIP API 的核心用法。本指南将引导您完成首次 API 调用的全过程。
API 调用流程
第一步:获取 API 密钥
在开始调用 API 之前,您需要先拥有一个有效的 apikey。
- 联系商务人员获取apikey。
- 妥善保管此密钥,它将在所有 API 请求中用于身份验证。
注意: 代理 IP 使用时需要做授权验证,支持账号密码验证,请确保您的使用方式符合平台要求[citation:6]。
第二步:初始化客户端
使用您获得的 apikey 初始化 SDK 客户端。以下是最简单的初始化示例:
// 基础配置
const config = {
apiKey: "your_apikey_here", // 替换为您的真实 API 密钥
baseUrl: "http://smartcheapip.com/api/v1/"
};
// 初始化客户端
const client = new ProxyClient(config);
第三步:调用核心接口
完成初始化后,您可以立即开始调用 API。我们建议从创建流量线路开始:
// 创建一个美国的流量线路,在线时长60分钟
try {
const account = await client.createAccount("US", 60);
console.log("创建成功!", account);
console.log(`代理地址: ${account.proxy_ip}:${account.http_port}`);
} catch (error) {
console.error("创建失败:", error.message);
}
如果一切正常,您将获得一个包含代理服务器地址、端口和密码的完整流量线路信息。
下一步建议
成功创建流量线路后,您可以:
- 查阅 接口详情 部分,了解如何查询账户列表、获取流量使用情况等。
- 查看 使用示例 部分,获取 Go、Python、Java 等语言的完整代码示例。
- 根据业务需要,设置代理授权(白名单或账密验证)以确保正常使用[citation:6]。
需要帮助?
如果在快速入门过程中遇到任何问题:
- 请仔细检查
apikey是否正确无误。 - 确认网络连接可以正常访问 API 端点。
- 查阅本页面的其他章节,或联系技术支持。
Get started with SmartCheapIP API in minutes. This guide walks you through making your first API call.
API Call Flow
Step 1: Get Your API Key
Before making API calls, you need a valid apikey.
- Contact Sales for an API key.
- Keep this key secure, as it will be used for authentication in all API requests.
Note: Proxy IP usage requires authorization verification, supporting either username/password methods. Ensure your usage complies with platform requirements[citation:6].
Step 2: Initialize the Client
Use your obtained apikey to initialize the SDK client. Here's the simplest example:
// Basic configuration
const config = {
apiKey: "your_apikey_here", // Replace with your real API key
baseUrl: "http://smartcheapip.com/api/v1/"
};
// Initialize client
const client = new ProxyClient(config);
Step 3: Call Core API
After initialization, you can start calling APIs immediately. We recommend starting with creating a flow account:
// Create a US flow account online time for 60 minutes
try {
const account = await client.createAccount("US", 60);
console.log("Success!", account);
console.log(`Proxy Address: ${account.proxy_ip}:${account.http_port}`);
} catch (error) {
console.error("Failed:", error.message);
}
If everything works, you'll receive complete flow account information including proxy server address, port, and password.
Next Steps
After successfully creating a flow account, you can:
- Check the API Details section to learn how to query account lists, get traffic usage, etc.
- Visit the Examples section for complete code samples in Go, Python, Java, etc.
- Set up proxy authorization (whitelist or credentials) as needed for proper usage[citation:6].
Need Help?
If you encounter any issues during quick start:
- Double-check that your
apikeyis correct. - Ensure network connectivity to the API endpoint.
- Refer to other sections of this documentation or contact support.
接口详情
API Details
1. 创建流量线路
创建指定国家和TTL的流量线路。
接口地址: POST /accounts/create
请求参数:
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| country | string | 是 | 国家代码(如:US, UK, JP等) |
| ttl | int | 是 | 在线时长(分钟) |
请求示例:
//golang
accounts, err := client.CreateAccount("US", 60)
响应示例:
{
"code": 0,
"data": [
{
"account_id": 123456,
"account": "Account123456",
"proxy_ip": "192.168.1.100",
"s5_port": 1080,
"http_port": 8080,
"password": "secure_password_123",
"country": "US",
"ttl": 60,
"traffic_used": 0
}
]
}
2. 获取账户列表
获取已创建的流量线路列表,支持按国家筛选和分页。
接口地址: POST /accounts/get_list
请求参数:
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| country | string | 否 | "" | 国家代码筛选(如:US, UK, JP等) |
| offset | int | 否 | 0 | 分页偏移量 |
| limit | int | 否 | 10 | 每页数量 |
请求示例:
//golang
// 获取所有账户
accounts, err := client.GetAccountList("", 0, 10)
// 获取美国账户,第2页,每页20条
accounts, err := client.GetAccountList("US", 20, 20)
响应示例:
{
"code": 0,
"data": [
{
"account_id": 123456,
"account": "Account123456",
"proxy_ip": "192.168.1.100",
"s5_port": 1080,
"http_port": 8080,
"password": "secure_password_123",
"country": "US",
"ttl": 60,
"traffic_used": 1024
},
{
"account_id": 123457,
"account": "Account23456",
"proxy_ip": "192.168.1.101",
"s5_port": 1081,
"http_port": 8081,
"password": "secure_password_456",
"country": "UK",
"ttl": 120,
"traffic_used": 2048
}
]
}
1. Create Flow Line
Create a flow line with specified country and TTL.
Endpoint: POST /accounts/create
Request Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| country | string | Yes | Country code (e.g., US, UK, JP, etc.) |
| ttl | int | Yes | online time(minutes) |
Request Example:
//golang
accounts, err := client.CreateAccount("US", 60)
Response Example:
{
"code": 0,
"data": [
{
"account_id": 123456,
"account": "Account123456",
"proxy_ip": "192.168.1.100",
"s5_port": 1080,
"http_port": 8080,
"password": "secure_password_123",
"country": "US",
"ttl": 60,
"traffic_used": 0
}
]
}
2. Get Account List
Get the list of created flow lines, supports filtering by country and pagination.
Endpoint: POST /accounts/get_list
Request Parameters:
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| country | string | No | "" | Country code filter (e.g., US, UK, JP, etc.) |
| offset | int | No | 0 | Pagination offset |
| limit | int | No | 10 | Items per page |
Request Example:
//golang
// Get all accounts
accounts, err := client.GetAccountList("", 0, 10)
// Get US accounts, page 2, 20 items per page
accounts, err := client.GetAccountList("US", 20, 20)
Response Example:
{
"code": 0,
"data": [
{
"account_id": 123456,
"account": "Account123456",
"proxy_ip": "192.168.1.100",
"s5_port": 1080,
"http_port": 8080,
"password": "secure_password_123",
"country": "US",
"ttl": 60,
"traffic_used": 1024
},
{
"account_id": 123457,
"account": "Account23456",
"proxy_ip": "192.168.1.101",
"s5_port": 1081,
"http_port": 8081,
"password": "secure_password_456",
"country": "UK",
"ttl": 120,
"traffic_used": 2048
}
]
}
HTTP/SOCKS5 代理使用文档
HTTP/SOCKS5 Proxy Usage Documentation
概述
本文档详细说明如何使用 SmartCheapIP 服务创建的 HTTP 和 SOCKS5 代理。
重要提示: 文档中示例出现的所有 IP 和端口以实际接口返回为准。
代理连接信息
创建代理账户后,您将获得以下信息,其中包括了代理服务器地址和端口,还有账号密码:
{
"account_id": 123456,
"account": "Account12345",
"proxy_ip": "45.76.189.214",
"s5_port": 1080,
"http_port": 8080,
"password": "secure_password_123",
"country": "US",
"ttl": 60
}
代理服务器地址格式:
- HTTP代理:
http://用户名:密码@代理IP:HTTP端口 - SOCKS5代理:
socks5://用户名:密码@代理IP:SOCKS5端口
示例:
HTTP代理: http://Account12345:secure_password_123@45.76.189.214:8080 SOCKS5代理: socks5://Account12345:secure_password_123@45.76.189.214:1080
使用 Session 固定 IP
如果需要在一定时间内固定使用某个 IP,可以使用 Session。在账户名后面加上下划线和 Session 名,即可在下次连接时,继续使用之前用这个 Session 获取的 IP。
注意: Session 的有效期最长为 20 分钟。
示例:
HTTP代理: http://Account12345_mysession:secure_password_123@45.76.189.214:8080 SOCKS5代理: socks5://Account12345_mysession:secure_password_123@45.76.189.214:1080
各语言/工具使用示例
Python - 使用 requests 库(HTTP代理)
import requests
# 代理配置
proxy_ip = "45.76.189.214"
http_port = 8080
username = "proxy_user_001"
password = "secure_password_123"
# 构建代理URL
http_proxy = f"http://{username}:{password}@{proxy_ip}:{http_port}"
proxies = {
'http': http_proxy,
'https': http_proxy
}
try:
# 测试代理连接
response = requests.get(
'https://httpbin.org/ip',
proxies=proxies,
timeout=30
)
if response.status_code == 200:
print("✅ 代理连接成功!")
print(f"当前IP: {response.json()['origin']}")
else:
print(f"❌ 请求失败,状态码: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"❌ 代理连接异常: {e}")
PHP - 使用 cURL(HTTP代理)
<?php
function testHttpProxy($proxyIp, $httpPort, $username, $password) {
$proxyUrl = "http://{$username}:{$password}@{$proxyIp}:{$httpPort}";
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => "https://httpbin.org/ip",
CURLOPT_PROXY => $proxyUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_USERAGENT => 'Mozilla/5.0'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
echo "❌ cURL错误: " . $error . "\n";
return false;
}
if ($httpCode === 200) {
$data = json_decode($response, true);
echo "✅ HTTP代理连接成功!\n";
echo "当前IP: " . $data['origin'] . "\n";
return $data;
} else {
echo "❌ HTTP请求失败,状态码: " . $httpCode . "\n";
return false;
}
}
// 使用示例
testHttpProxy('45.76.189.214', 8080, 'proxy_user_001', 'secure_password_123');
?>
Node.js - 使用 axios(HTTP代理)
const axios = require('axios');
const HttpsProxyAgent = require('https-proxy-agent');
// 代理配置
const proxyConfig = {
host: '45.76.189.214',
port: 8080,
auth: { username: 'proxy_user_001', password: 'secure_password_123' }
};
const agent = new HttpsProxyAgent(
`http://${proxyConfig.auth.username}:${proxyConfig.auth.password}@${proxyConfig.host}:${proxyConfig.port}`
);
async function testHttpProxy() {
try {
const response = await axios.get('https://httpbin.org/ip', {
httpsAgent: agent,
timeout: 30000
});
console.log('✅ HTTP代理连接成功!');
console.log('当前IP:', response.data.origin);
} catch (error) {
console.error('❌ HTTP代理连接失败:', error.message);
}
}
testHttpProxy();
Java - 使用 HttpClient(HTTP代理)
import java.net.*;
import java.net.http.*;
import java.time.Duration;
import java.util.Base64;
public class HttpProxyExample {
public static void main(String[] args) {
String proxyHost = "45.76.189.214";
int proxyPort = 8080;
String username = "proxy_user_001";
String password = "secure_password_123";
// 创建代理
Proxy proxy = new Proxy(Proxy.Type.HTTP,
new InetSocketAddress(proxyHost, proxyPort));
// 创建HTTP客户端
HttpClient client = HttpClient.newBuilder()
.proxy(ProxySelector.of(new InetSocketAddress(proxyHost, proxyPort)))
.connectTimeout(Duration.ofSeconds(30))
.build();
// 创建认证头
String auth = username + ":" + password;
String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
// 创建请求
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://httpbin.org/ip"))
.header("Proxy-Authorization", "Basic " + encodedAuth)
.timeout(Duration.ofSeconds(30))
.build();
try {
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
System.out.println("✅ HTTP代理连接成功!");
System.out.println("响应: " + response.body());
} catch (Exception e) {
System.err.println("❌ HTTP代理连接失败: " + e.getMessage());
}
}
}
Go - 使用 net/http 包(HTTP代理)
package main
import (
"fmt"
"net/http"
"net/url"
"time"
)
func main() {
proxyURL, _ := url.Parse("http://proxy_user_001:secure_password_123@45.76.189.214:8080")
client := &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
},
}
resp, err := client.Get("https://httpbin.org/ip")
if err != nil {
fmt.Printf("❌ HTTP代理连接失败: %v\n", err)
return
}
defer resp.Body.Close()
fmt.Println("✅ HTTP代理连接成功!")
// 处理响应...
}
Go - 使用 SOCKS5 代理
package main
import (
"fmt"
"net"
"net/http"
"time"
"golang.org/x/net/proxy"
)
func main() {
// 创建SOCKS5拨号器
dialer, err := proxy.SOCKS5("tcp", "45.76.189.214:1080",
&proxy.Auth{
User: "proxy_user_001",
Password: "secure_password_123",
},
&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
},
)
if err != nil {
fmt.Printf("❌ SOCKS5代理创建失败: %v\n", err)
return
}
client := &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
Dial: dialer.Dial,
},
}
resp, err := client.Get("https://httpbin.org/ip")
if err != nil {
fmt.Printf("❌ SOCKS5代理连接失败: %v\n", err)
return
}
defer resp.Body.Close()
fmt.Println("✅ SOCKS5代理连接成功!")
}
cURL - 命令行使用 HTTP 代理
# 使用HTTP代理
curl -x "http://proxy_user_001:secure_password_123@45.76.189.214:8080" \
"https://httpbin.org/ip" -p
# 或者使用环境变量
export http_proxy="http://proxy_user_001:secure_password_123@45.76.189.214:8080"
export https_proxy="http://proxy_user_001:secure_password_123@45.76.189.214:8080"
curl "https://httpbin.org/ip"
cURL - 命令行使用 SOCKS5 代理
# 使用SOCKS5代理(需要支持SOCKS的curl版本)
curl -x "socks5://proxy_user_001:secure_password_123@45.76.189.214:1080" \
"https://httpbin.org/ip"
Chrome/Firefox 手动配置
- 打开浏览器设置
- 搜索"代理设置"
- 手动配置代理:
- HTTP代理:
45.76.189.214:8080 - SOCKS主机:
45.76.189.214:1080 - 用户名:
proxy_user_001 - 密码:
secure_password_123
使用 SwitchyOmega 扩展(Chrome/Firefox)
- 安装 SwitchyOmega 扩展
- 创建新的情景模式
- 配置代理服务器:
- 协议: HTTP 或 SOCKS5
- 服务器:
45.76.189.214 - 端口:
8080(HTTP) 或1080(SOCKS5) - 用户名:
proxy_user_001 - 密码:
secure_password_123
PHP - 使用 cURL(HTTP代理)
<?php
function testHttpProxy($proxyIp, $httpPort, $username, $password) {
$proxyUrl = "http://{$username}:{$password}@{$proxyIp}:{$httpPort}";
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => "https://httpbin.org/ip",
CURLOPT_PROXY => $proxyUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_USERAGENT => 'Mozilla/5.0'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
echo "❌ cURL错误: " . $error . "\n";
return false;
}
if ($httpCode === 200) {
$data = json_decode($response, true);
echo "✅ HTTP代理连接成功!\n";
echo "当前IP: " . $data['origin'] . "\n";
return $data;
} else {
echo "❌ HTTP请求失败,状态码: " . $httpCode . "\n";
return false;
}
}
// 使用示例
testHttpProxy('45.76.189.214', 8080, 'proxy_user_001', 'secure_password_123');
?>
PHP - SOCKS5 代理使用(需要 socks5 扩展)
<?php
function useSocks5Proxy($proxyIp, $socks5Port, $username, $password) {
if (!extension_loaded('socks5')) {
echo "❌ 请先安装socks5扩展: pecl install socks5\n";
return false;
}
$context = stream_context_create([
'socks5' => [
'proxy' => "tcp://{$proxyIp}:{$socks5Port}",
'username' => $username,
'password' => $password,
'timeout' => 30
]
]);
try {
$response = file_get_contents('https://httpbin.org/ip', false, $context);
$data = json_decode($response, true);
echo "✅ SOCKS5代理连接成功!\n";
echo "当前IP: " . $data['origin'] . "\n";
return $data;
} catch (Exception $e) {
echo "❌ SOCKS5代理连接失败: " . $e->getMessage() . "\n";
return false;
}
}
// 使用示例
useSocks5Proxy('45.76.189.214', 1080, 'proxy_user_001', 'secure_password_123');
?>
Node.js - 使用 axios(HTTP代理)
const axios = require('axios');
const HttpsProxyAgent = require('https-proxy-agent');
// 代理配置
const proxyConfig = {
host: '45.76.189.214',
port: 8080,
auth: {
username: 'proxy_user_001',
password: 'secure_password_123'
}
};
const agent = new HttpsProxyAgent(
`http://${proxyConfig.auth.username}:${proxyConfig.auth.password}@${proxyConfig.host}:${proxyConfig.port}`
);
async function testHttpProxy() {
try {
const response = await axios.get('https://httpbin.org/ip', {
httpsAgent: agent,
timeout: 30000
});
console.log('✅ HTTP代理连接成功!');
console.log('当前IP:', response.data.origin);
} catch (error) {
console.error('❌ HTTP代理连接失败:', error.message);
}
}
testHttpProxy();
Node.js - 使用 socks-proxy-agent(SOCKS5代理)
const axios = require('axios');
const SocksProxyAgent = require('socks-proxy-agent');
// SOCKS5代理配置
const socksProxy = `socks5://proxy_user_001:secure_password_123@45.76.189.214:1080`;
const agent = new SocksProxyAgent(socksProxy);
async function testSocks5Proxy() {
try {
const response = await axios.get('https://httpbin.org/ip', {
httpsAgent: agent,
timeout: 30000
});
console.log('✅ SOCKS5代理连接成功!');
console.log('当前IP:', response.data.origin);
} catch (error) {
console.error('❌ SOCKS5代理连接失败:', error.message);
}
}
testSocks5Proxy();
常见问题解答
Q: 代理连接失败怎么办?
A: 检查以下项目:
- 代理账户是否有效
- 用户名和密码是否正确
- 代理服务器IP和端口是否正确
- 本地网络是否允许连接到代理服务器
Q: HTTP代理和SOCKS5代理有什么区别?
A:
- HTTP代理: 只能代理HTTP/HTTPS流量,更容易使用
- SOCKS5代理: 可以代理所有TCP流量,包括HTTP、FTP、游戏等,更通用
Q: 如何测试代理是否工作?
A: 使用以下测试命令:
# 测试当前IP
curl -x http://用户名:密码@代理IP:端口 http://httpbin.org/ip
curl -x http://用户名:密码@代理IP:端口 https://api.ipify.org?format=json
Q: 支持哪些协议?
A:
- ✅ HTTP/HTTPS
- ✅ SOCKS5
- ✅ FTP(通过SOCKS5)
- ✅ 游戏连接(通过SOCKS5)
- ✅ 数据库连接(通过SOCKS5)
技术支持
如果遇到代理使用问题,请提供以下信息:
- 代理账户信息(隐藏密码)
- 错误日志或截图
- 使用的编程语言和库版本
- 网络环境描述
Overview
This document details how to use HTTP and SOCKS5 proxies created through the SmartCheapIP service.
Important: All IPs and ports in example code are for demonstration only; use actual values returned by the API.
Proxy Connection Information
After creating a proxy account, you will receive information including proxy server address, ports, and credentials:
{
"account_id": 123456,
"account": "Account12345",
"proxy_ip": "45.76.189.214",
"s5_port": 1080,
"http_port": 8080,
"password": "secure_password_123",
"country": "US",
"ttl": 60
}
Proxy Server URL Format:
- HTTP Proxy:
http://username:password@proxyIP:HTTPport - SOCKS5 Proxy:
socks5://username:password@proxyIP:SOCKS5port
Example:
HTTP Proxy: http://Account12345:secure_password_123@45.76.189.214:8080 SOCKS5 Proxy: socks5://Account12345:secure_password_123@45.76.189.214:1080
Using Session to Fix IP
If you need to use the same IP address for a period of time, you can use Session. Append an underscore and session name to the account name to continue using the IP obtained with that session.
Note: Session validity is up to 20 minutes maximum.
Example:
HTTP Proxy: http://Account12345_mysession:secure_password_123@45.76.189.214:8080 SOCKS5 Proxy: socks5://Account12345_mysession:secure_password_123@45.76.189.214:1080
Language/Tool Examples
Python - Using requests library (HTTP Proxy)
import requests
# Proxy configuration
proxy_ip = "45.76.189.214"
http_port = 8080
username = "proxy_user_001"
password = "secure_password_123"
# Build proxy URL
http_proxy = f"http://{username}:{password}@{proxy_ip}:{http_port}"
proxies = {
'http': http_proxy,
'https': http_proxy
}
try:
# Test proxy connection
response = requests.get(
'https://httpbin.org/ip',
proxies=proxies,
timeout=30
)
if response.status_code == 200:
print("✅ Proxy connection successful!")
print(f"Current IP: {response.json()['origin']}")
else:
print(f"❌ Request failed, status code: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"❌ Proxy connection error: {e}")
PHP - Using cURL (HTTP Proxy)
<?php
function testHttpProxy($proxyIp, $httpPort, $username, $password) {
$proxyUrl = "http://{$username}:{$password}@{$proxyIp}:{$httpPort}";
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => "https://httpbin.org/ip",
CURLOPT_PROXY => $proxyUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_USERAGENT => 'Mozilla/5.0'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
echo "❌ cURL error: " . $error . "\n";
return false;
}
if ($httpCode === 200) {
$data = json_decode($response, true);
echo "✅ HTTP proxy connection successful!\n";
echo "Current IP: " . $data['origin'] . "\n";
return $data;
} else {
echo "❌ HTTP request failed, status code: " . $httpCode . "\n";
return false;
}
}
// Usage example
testHttpProxy('45.76.189.214', 8080, 'proxy_user_001', 'secure_password_123');
?>
PHP - SOCKS5 Proxy Usage (requires socks5 extension)
<?php
function useSocks5Proxy($proxyIp, $socks5Port, $username, $password) {
if (!extension_loaded('socks5')) {
echo "❌ Please install socks5 extension first: pecl install socks5\n";
return false;
}
$context = stream_context_create([
'socks5' => [
'proxy' => "tcp://{$proxyIp}:{$socks5Port}",
'username' => $username,
'password' => $password,
'timeout' => 30
]
]);
try {
$response = file_get_contents('https://httpbin.org/ip', false, $context);
$data = json_decode($response, true);
echo "✅ SOCKS5 proxy connection successful!\n";
echo "Current IP: " . $data['origin'] . "\n";
return $data;
} catch (Exception $e) {
echo "❌ SOCKS5 proxy connection failed: " . $e->getMessage() . "\n";
return false;
}
}
// Usage example
useSocks5Proxy('45.76.189.214', 1080, 'proxy_user_001', 'secure_password_123');
?>
Node.js - Using axios (HTTP Proxy)
const axios = require('axios');
const HttpsProxyAgent = require('https-proxy-agent');
// Proxy configuration
const proxyConfig = {
host: '45.76.189.214',
port: 8080,
auth: {
username: 'proxy_user_001',
password: 'secure_password_123'
}
};
const agent = new HttpsProxyAgent(
`http://${proxyConfig.auth.username}:${proxyConfig.auth.password}@${proxyConfig.host}:${proxyConfig.port}`
);
async function testHttpProxy() {
try {
const response = await axios.get('https://httpbin.org/ip', {
httpsAgent: agent,
timeout: 30000
});
console.log('✅ HTTP proxy connection successful!');
console.log('Current IP:', response.data.origin);
} catch (error) {
console.error('❌ HTTP proxy connection failed:', error.message);
}
}
testHttpProxy();
Node.js - Using socks-proxy-agent (SOCKS5 Proxy)
const axios = require('axios');
const SocksProxyAgent = require('socks-proxy-agent');
// SOCKS5 proxy configuration
const socksProxy = `socks5://proxy_user_001:secure_password_123@45.76.189.214:1080`;
const agent = new SocksProxyAgent(socksProxy);
async function testSocks5Proxy() {
try {
const response = await axios.get('https://httpbin.org/ip', {
httpsAgent: agent,
timeout: 30000
});
console.log('✅ SOCKS5 proxy connection successful!');
console.log('Current IP:', response.data.origin);
} catch (error) {
console.error('❌ SOCKS5 proxy connection failed:', error.message);
}
}
testSocks5Proxy();
Java - Using HttpClient (HTTP Proxy)
import java.net.*;
import java.net.http.*;
import java.time.Duration;
import java.util.Base64;
public class HttpProxyExample {
public static void main(String[] args) {
String proxyHost = "45.76.189.214";
int proxyPort = 8080;
String username = "proxy_user_001";
String password = "secure_password_123";
// Create proxy
Proxy proxy = new Proxy(Proxy.Type.HTTP,
new InetSocketAddress(proxyHost, proxyPort));
// Create HTTP client
HttpClient client = HttpClient.newBuilder()
.proxy(ProxySelector.of(new InetSocketAddress(proxyHost, proxyPort)))
.connectTimeout(Duration.ofSeconds(30))
.build();
// Create authentication header
String auth = username + ":" + password;
String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
// Create request
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://httpbin.org/ip"))
.header("Proxy-Authorization", "Basic " + encodedAuth)
.timeout(Duration.ofSeconds(30))
.build();
try {
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
System.out.println("✅ HTTP proxy connection successful!");
System.out.println("Response: " + response.body());
} catch (Exception e) {
System.err.println("❌ HTTP proxy connection failed: " + e.getMessage());
}
}
}
Go - Using net/http package (HTTP Proxy)
package main
import (
"fmt"
"net/http"
"net/url"
"time"
)
func main() {
proxyURL, _ := url.Parse("http://proxy_user_001:secure_password_123@45.76.189.214:8080")
client := &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
},
}
resp, err := client.Get("https://httpbin.org/ip")
if err != nil {
fmt.Printf("❌ HTTP proxy connection failed: %v\n", err)
return
}
defer resp.Body.Close()
fmt.Println("✅ HTTP proxy connection successful!")
// Process response...
}
Go - Using SOCKS5 Proxy
package main
import (
"fmt"
"net"
"net/http"
"time"
"golang.org/x/net/proxy"
)
func main() {
// Create SOCKS5 dialer
dialer, err := proxy.SOCKS5("tcp", "45.76.189.214:1080",
&proxy.Auth{
User: "proxy_user_001",
Password: "secure_password_123",
},
&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
},
)
if err != nil {
fmt.Printf("❌ SOCKS5 proxy creation failed: %v\n", err)
return
}
client := &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
Dial: dialer.Dial,
},
}
resp, err := client.Get("https://httpbin.org/ip")
if err != nil {
fmt.Printf("❌ SOCKS5 proxy connection failed: %v\n", err)
return
}
defer resp.Body.Close()
fmt.Println("✅ SOCKS5 proxy connection successful!")
}
cURL - Command Line HTTP Proxy
# Using HTTP proxy
curl -x "http://proxy_user_001:secure_password_123@45.76.189.214:8080" \
"https://httpbin.org/ip" -p
# Or using environment variables
export http_proxy="http://proxy_user_001:secure_password_123@45.76.189.214:8080"
export https_proxy="http://proxy_user_001:secure_password_123@45.76.189.214:8080"
curl "https://httpbin.org/ip"
cURL - Command Line SOCKS5 Proxy
# Using SOCKS5 proxy (requires curl with SOCKS support)
curl -x "socks5://proxy_user_001:secure_password_123@45.76.189.214:1080" \
"https://httpbin.org/ip"
Chrome/Firefox Manual Configuration
- Open browser settings
- Search for "proxy settings"
- Configure proxy manually:
- HTTP Proxy:
45.76.189.214:8080 - SOCKS Host:
45.76.189.214:1080 - Username:
proxy_user_001 - Password:
secure_password_123
Using SwitchyOmega Extension (Chrome/Firefox)
- Install SwitchyOmega extension
- Create new profile
- Configure proxy server:
- Protocol: HTTP or SOCKS5
- Server:
45.76.189.214 - Port:
8080(HTTP) or1080(SOCKS5) - Username:
proxy_user_001 - Password:
secure_password_123
Frequently Asked Questions
Q: What to do if proxy connection fails?
A: Check the following:
- Whether the proxy account is valid
- Whether username and password are correct
- Whether proxy server IP and port are correct
- Whether local network allows connection to proxy server
Q: What's the difference between HTTP proxy and SOCKS5 proxy?
A:
- HTTP Proxy: Can only proxy HTTP/HTTPS traffic, easier to use
- SOCKS5 Proxy: Can proxy all TCP traffic including HTTP, FTP, games, etc., more versatile
Q: How to test if proxy is working?
A: Use the following test commands:
# Test current IP
curl -x http://username:password@proxyIP:port http://httpbin.org/ip
curl -x http://username:password@proxyIP:port https://api.ipify.org?format=json
Q: What protocols are supported?
A:
- ✅ HTTP/HTTPS
- ✅ SOCKS5
- ✅ FTP (via SOCKS5)
- ✅ Game connections (via SOCKS5)
- ✅ Database connections (via SOCKS5)
Technical Support
If you encounter proxy usage issues, please provide:
- Proxy account information (hide password)
- Error logs or screenshots
- Programming language and library versions used
- Network environment description
响应格式
Response Format
成功响应
{
"code": 0,
"data": { ... },
"msg": "success"
}
错误响应
{
"code": -1,
"data": null,
"msg": "错误描述信息"
}
响应码说明
响应码为0表示成功,其他都表示失败,具体错误信息请从msg字段中获取。
Success Response
{
"code": 0,
"data": { ... },
"msg": "success"
}
Error Response
{
"code": -1,
"data": null,
"msg": "Error description"
}
Response Code Explanation
A response code of 0 indicates success, all others indicate failure. Specific error information can be obtained from the msg field.
注意事项
Notes
- API Key安全: 请妥善保管API Key,避免泄露给未经授权的第三方。
- 请求频率: 建议控制请求频率,避免过于频繁的调用,以免触发限流机制。
- 错误处理: 建议对所有API调用进行异常捕获和错误处理,确保程序的健壮性。
- 超时设置: 根据网络情况合理设置超时时间,建议设置为10-30秒。
- 代理使用: 创建的流量线路信息请妥善保管,避免泄露。代理密码建议定期更换。
- 流量监控: 定期检查流量使用情况,避免流量耗尽影响业务。
- 版本兼容性: 请注意API版本,不同版本之间可能存在不兼容的变更。
技术支持
如有问题请联系技术支持。
- API Key Security: Please keep your API Key secure and avoid leaking it to unauthorized third parties.
- Request Frequency: It is recommended to control request frequency to avoid triggering rate limiting mechanisms.
- Error Handling: It is recommended to implement exception catching and error handling for all API calls to ensure program robustness.
- Timeout Settings: Set appropriate timeout values based on network conditions, recommended 10-30 seconds.
- Proxy Usage: Please keep the created flow line information secure and avoid leakage. It is recommended to change proxy passwords regularly.
- Traffic Monitoring: Regularly check traffic usage to avoid service disruption due to traffic exhaustion.
- Version Compatibility: Please note the API version, as incompatible changes may exist between different versions.
Technical Support
If you have any questions, please contact technical support.
Go SDK
Go SDK
1. 下载Go依赖
在使用SmartCheapIP Go客户端之前,需要先安装依赖包。点击下载
系统要求:Go 1.16或更高版本
2. 初始化客户端
package main
import (
"fmt"
"log"
"time"
"proxyclient-go/client"
)
func main() {
// 创建客户端配置
config := client.Config{
APIKey: "your_api_key_here",
Timeout: 30 * time.Second,
}
// 创建API客户端
apiClient, err := client.NewClient(config)
if err != nil {
log.Fatalf("创建客户端失败: %v", err)
}
// 使用示例
runExamples(apiClient)
}
3. 完整使用示例
func runExamples(client *client.Client) {
fmt.Println("=== ProxyClient API 使用示例 ===")
// 示例1: 创建流量线路
fmt.Println("\n1. 创建流量线路...")
accounts, err := client.CreateAccount("US", 60)
if err != nil {
fmt.Printf("创建账户失败: %v\n", err)
} else {
fmt.Printf("成功创建 %d 个账户:\n", len(accounts))
for _, account := range accounts {
fmt.Printf(" - 账户: %s, 代理: %s:%d, 国家: %s\n",
account.Account, account.ProxyServer, account.HttpPort, account.Country)
}
}
// 示例2: 获取账户列表
fmt.Println("\n2. 获取账户列表...")
accountList, err := client.GetAccountList("US", 0, 10)
if err != nil {
fmt.Printf("获取账户列表失败: %v\n", err)
} else {
fmt.Printf("获取到 %d 个账户:\n", len(accountList))
for _, account := range accountList {
fmt.Printf(" - ID: %d, 账户: %s, 已用流量: %d\n",
account.AccountId, account.Account, account.TrafficUsed)
}
}
// 示例3: 获取套餐信息
fmt.Println("\n3. 获取套餐信息...")
packageInfo, err := client.GetPackageInfo()
if err != nil {
fmt.Printf("获取套餐信息失败: %v\n", err)
} else {
fmt.Printf("总流量: %d %s\n", packageInfo.TrafficTotal, packageInfo.Unit)
fmt.Printf("已使用: %d %s\n", packageInfo.TrafficUsed, packageInfo.Unit)
fmt.Printf("剩余流量: %d %s\n", packageInfo.TrafficRemain, packageInfo.Unit)
fmt.Printf("账户数量: %d\n", packageInfo.FlowAccountCount)
}
// 示例4: 查询流量明细
fmt.Println("\n4. 查询流量明细...")
trafficDetails, err := client.GetTrafficDetail(
"", // 查询所有账户
"2024-01-01 00:00:00",
"2024-01-31 23:59:59",
)
if err != nil {
fmt.Printf("查询流量明细失败: %v\n", err)
} else {
fmt.Printf("查询到 %d 条流量记录:\n", len(trafficDetails))
for i, detail := range trafficDetails {
if i >= 3 { // 只显示前3条
break
}
fmt.Printf(" - 日期: %s, 账户: %s, 流量: %d\n",
detail.Date, detail.Account, detail.Traffic)
}
}
}
1. Download Go Dependencies
Before using the SmartCheapIP Go client, dowload the dependencies. click to download
2. Initialize Client
package main
import (
"fmt"
"log"
"time"
"proxyclient-go/client"
)
func main() {
// Create client configuration
config := client.Config{
APIKey: "your_api_key_here",
Timeout: 30 * time.Second,
}
// Create API client
apiClient, err := client.NewClient(config)
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
// Usage examples
runExamples(apiClient)
}
3. Complete Usage Example
func runExamples(client *client.Client) {
fmt.Println("=== ProxyClient API Usage Example ===")
// Example 1: Create flow line
fmt.Println("\n1. Creating flow line...")
accounts, err := client.CreateAccount("US", 60)
if err != nil {
fmt.Printf("Failed to create account: %v\n", err)
} else {
fmt.Printf("Successfully created %d accounts:\n", len(accounts))
for _, account := range accounts {
fmt.Printf(" - Account: %s, Proxy: %s:%d, Country: %s\n",
account.Account, account.ProxyServer, account.HttpPort, account.Country)
}
}
// Example 2: Get account list
fmt.Println("\n2. Getting account list...")
accountList, err := client.GetAccountList("US", 0, 10)
if err != nil {
fmt.Printf("Failed to get account list: %v\n", err)
} else {
fmt.Printf("Got %d accounts:\n", len(accountList))
for _, account := range accountList {
fmt.Printf(" - ID: %d, Account: %s, Traffic used: %d\n",
account.AccountId, account.Account, account.TrafficUsed)
}
}
// Example 3: Get package info
fmt.Println("\n3. Getting package info...")
packageInfo, err := client.GetPackageInfo()
if err != nil {
fmt.Printf("Failed to get package info: %v\n", err)
} else {
fmt.Printf("Total traffic: %d %s\n", packageInfo.TrafficTotal, packageInfo.Unit)
fmt.Printf("Used: %d %s\n", packageInfo.TrafficUsed, packageInfo.Unit)
fmt.Printf("Remaining traffic: %d %s\n", packageInfo.TrafficRemain, packageInfo.Unit)
fmt.Printf("Account count: %d\n", packageInfo.FlowAccountCount)
}
// Example 4: Query traffic details
fmt.Println("\n4. Querying traffic details...")
trafficDetails, err := client.GetTrafficDetail(
"", // Query all accounts
"2024-01-01 00:00:00",
"2024-01-31 23:59:59",
)
if err != nil {
fmt.Printf("Failed to query traffic details: %v\n", err)
} else {
fmt.Printf("Found %d traffic records:\n", len(trafficDetails))
for i, detail := range trafficDetails {
if i >= 3 { // Only show first 3
break
}
fmt.Printf(" - Date: %s, Account: %s, Traffic: %d\n",
detail.Date, detail.Account, detail.Traffic)
}
}
}
Python SDK
Python Language SDK
1. 下载Python SDK
在使用SmartCheapIP Python客户端之前,需要先安装SDK。点击下载
系统要求:Python 3.7或更高版本,pip
2. 初始化客户端
from proxy_api import *
api = Api(apikey='your_apikey_here')
3. 完整使用示例
import time
from datetime import datetime, timedelta
from proxy_api import *
class ProxyClientManager:
"""ProxyClient 代理管理类"""
def __init__(self, api_key):
self.api = Api(apikey=api_key)
self.accounts = []
def create_multiple_accounts(self, countries, ttl=60):
"""批量创建多个国家的流量线路"""
created_accounts = []
for country in countries:
try:
print(f"正在创建 {country} 流量线路...")
account = self.api.create_account(country, ttl)
if account:
created_accounts.append(account)
print(f"✅ {country} 代理创建成功")
# 避免请求过于频繁
time.sleep(1)
except Exception as e:
print(f"❌ {country} 代理创建失败: {e}")
self.accounts.extend(created_accounts)
return created_accounts
def list_all_accounts(self):
"""列出所有账户并统计"""
try:
accounts = self.api.get_account_list()
if isinstance(accounts, list):
# 按国家统计
country_stats = {}
for account in accounts:
country = account.get('country', 'Unknown')
country_stats[country] = country_stats.get(country, 0) + 1
print(f"📊 账户统计:")
for country, count in country_stats.items():
print(f" {country}: {count} 个账户")
return accounts
else:
print("❌ 获取账户列表失败")
return []
except Exception as e:
print(f"❌ 获取账户列表失败: {e}")
return []
def monitor_traffic_usage(self):
"""监控流量使用情况"""
try:
# 获取套餐信息
package_info = self.api.get_package_info()
if isinstance(package_info, dict):
total = package_info.get('traffic_total', 0)
used = package_info.get('traffic_used', 0)
remain = package_info.get('traffic_remain', 0)
usage_percent = (used / total * 100) if total > 0 else 0
print(f"📈 流量使用情况:")
print(f" 总流量: {total} {package_info.get('unit', '')}")
print(f" 已使用: {used} ({usage_percent:.1f}%)")
print(f" 剩余流量: {remain}")
# 流量预警
if usage_percent > 80:
print("⚠️ 警告: 流量使用已超过80%!")
elif usage_percent > 95:
print("🚨 紧急: 流量即将用完!")
return package_info
except Exception as e:
print(f"❌ 获取流量信息失败: {e}")
return None
1. download Python SDK
Before using the SmartCheapIP Python client, you need to download the SDK first. click to download
System Requirements: Python 3.7 or higher
2. Initialize Client
from proxy_api import *
api = Api(apikey='your_apikey_here')
3. Complete Usage Example
import time
from datetime import datetime, timedelta
from proxy_api import *
class ProxyClientManager:
"""ProxyClient Proxy Management Class"""
def __init__(self, api_key):
self.api = Api(apikey=api_key)
self.accounts = []
def create_multiple_accounts(self, countries, ttl=60):
"""Batch create flow lines for multiple countries"""
created_accounts = []
for country in countries:
try:
print(f"Creating {country} flow line...")
account = self.api.create_account(country, ttl)
if account:
created_accounts.append(account)
print(f"✅ {country} proxy created successfully")
# Avoid too frequent requests
time.sleep(1)
except Exception as e:
print(f"❌ Failed to create {country} proxy: {e}")
self.accounts.extend(created_accounts)
return created_accounts
def list_all_accounts(self):
"""List all accounts with statistics"""
try:
accounts = self.api.get_account_list()
if isinstance(accounts, list):
# Statistics by country
country_stats = {}
for account in accounts:
country = account.get('country', 'Unknown')
country_stats[country] = country_stats.get(country, 0) + 1
print(f"📊 Account statistics:")
for country, count in country_stats.items():
print(f" {country}: {count} accounts")
return accounts
else:
print("❌ Failed to get account list")
return []
except Exception as e:
print(f"❌ Failed to get account list: {e}")
return []
def monitor_traffic_usage(self):
"""Monitor traffic usage"""
try:
# Get package information
package_info = self.api.get_package_info()
if isinstance(package_info, dict):
total = package_info.get('traffic_total', 0)
used = package_info.get('traffic_used', 0)
remain = package_info.get('traffic_remain', 0)
usage_percent = (used / total * 100) if total > 0 else 0
print(f"📈 Traffic usage:")
print(f" Total traffic: {total} {package_info.get('unit', '')}")
print(f" Used: {used} ({usage_percent:.1f}%)")
print(f" Remaining traffic: {remain}")
# Traffic warning
if usage_percent > 80:
print("⚠️ Warning: Traffic usage exceeds 80%!")
elif usage_percent > 95:
print("🚨 Emergency: Traffic almost exhausted!")
return package_info
except Exception as e:
print(f"❌ Failed to get traffic information: {e}")
return None
PHP SDK
PHP Language SDK
1. 下载PHP SDK
在使用SmartCheapIP PHP客户端之前,需要先安装SDK。点击下载
系统要求:PHP 7.4或更高版本,Composer
2. 初始化客户端
require_once 'proxy_client.php';
// 配置客户端
$config = new Config();
$config->apiKey = "your_apikey_here";
$config->timeout = 30;
// 创建客户端
$client = new ProxyClient($config);
3. 完整使用示例
require_once 'proxy_client.php';
// 配置客户端
$config = new Config();
$config->apiKey = "your_apikey_here";
$config->timeout = 30;
try {
// 创建客户端
$client = new ProxyClient($config);
echo "=== 创建流量线路 ===\n";
$accounts = $client->createAccount("US", 60);
echo "创建成功,账户数量: " . count($accounts) . "\n";
foreach ($accounts as $account) {
echo "账户: " . $account->account . ", 国家: " . $account->country . "\n";
}
echo "\n=== 获取流量线路列表 ===\n";
$accountList = $client->getAccountList("US", 0, 10);
echo "获取到 " . count($accountList) . " 个账户\n";
foreach ($accountList as $account) {
echo "账户ID: " . $account->account_id . ", 账号: " . $account->account .
", 代理IP: " . $account->proxy_ip . ", 端口: " . $account->s5_port . "\n";
}
echo "\n=== 获取套餐信息 ===\n";
$packageInfo = $client->getPackageInfo();
echo "总流量: " . $packageInfo->traffic_total . $packageInfo->unit . "\n";
echo "已使用: " . $packageInfo->traffic_used . $packageInfo->unit . "\n";
echo "剩余流量: " . $packageInfo->traffic_remain . $packageInfo->unit . "\n";
echo "账户数量: " . $packageInfo->flow_account_count . "\n";
echo "\n=== 查询流量明细 ===\n";
$trafficDetails = $client->getTrafficDetail(
"", // 空字符串表示查询全部账户
"2025-11-01 00:00:00",
"2025-11-30 23:59:59"
);
echo "查询到 " . count($trafficDetails) . " 条流量记录\n";
foreach ($trafficDetails as $detail) {
echo "日期: " . $detail->date . ", 账户: " . $detail->account .
", 流量: " . $detail->traffic . "\n";
}
// 示例5: 删除流量线路(请使用实际存在的账户名)
echo "\n=== 删除流量线路 ===\n";
try {
$result = $client->removeAccount("Account153300");
echo "删除结果: " . ($result ? "成功" : "失败") . "\n";
} catch (ApiException $e) {
echo "删除失败: " . $e->getMessage() . "\n";
}
} catch (ApiException $e) {
echo "API错误 [" . $e->getErrorCode() . "]: " . $e->getMessage() . "\n";
} catch (Exception $e) {
echo "系统错误: " . $e->getMessage() . "\n";
}
4. 错误处理示例
try{
// API调用代码
} catch (ApiException $e) {
echo "API错误 [" . $e->getErrorCode() . "]: " . $e->getMessage() . "\n";
} catch (Exception $e) {
echo "系统错误: " . $e->getMessage() . "\n";
}
1. download PHP SDK
Before using the SmartCheapIP PHP client, you need to download the SDK first. click to download
System Requirements: PHP 7.4 or higher
2. Initialize Client
require_once 'proxy_client.php';
// Configure client
$config = new Config();
$config->apiKey = "your_apikey_here";
$config->timeout = 30;
// Create client
$client = new ProxyClient($config);
3. Complete Usage Example
require_once 'proxy_client.php';
// Configure client
$config = new Config();
$config->apiKey = "your_apikey_here";
$config->timeout = 30;
try {
// Create client
$client = new ProxyClient($config);
echo "=== Create Flow Line ===\n";
$accounts = $client->createAccount("US", 60);
echo "Created successfully, account count: " . count($accounts) . "\n";
foreach ($accounts as $account) {
echo "Account: " . $account->account . ", Country: " . $account->country . "\n";
}
echo "\n=== Get Flow Line List ===\n";
$accountList = $client->getAccountList("US", 0, 10);
echo "Got " . count($accountList) . " accounts\n";
foreach ($accountList as $account) {
echo "Account ID: " . $account->account_id . ", Account: " . $account->account .
", Proxy IP: " . $account->proxy_ip . ", Port: " . $account->s5_port . "\n";
}
echo "\n=== Get Package Info ===\n";
$packageInfo = $client->getPackageInfo();
echo "Total traffic: " . $packageInfo->traffic_total . $packageInfo->unit . "\n";
echo "Used: " . $packageInfo->traffic_used . $packageInfo->unit . "\n";
echo "Remaining traffic: " . $packageInfo->traffic_remain . $packageInfo->unit . "\n";
echo "Account count: " . $packageInfo->flow_account_count . "\n";
echo "\n=== Query Traffic Details ===\n";
$trafficDetails = $client->getTrafficDetail(
"", // Empty string means query all accounts
"2025-11-01 00:00:00",
"2025-11-30 23:59:59"
);
echo "Found " . count($trafficDetails) . " traffic records\n";
foreach ($trafficDetails as $detail) {
echo "Date: " . $detail->date . ", Account: " . $detail->account .
", Traffic: " . $detail->traffic . "\n";
}
echo "\n=== Remove Flow Line ===\n";
try {
$result = $client->removeAccount("Account153300");
echo "Delete result: " . ($result ? "Success" : "Failed") . "\n";
} catch (ApiException $e) {
echo "Delete failed: " . $e->getMessage() . "\n";
}
} catch (ApiException $e) {
echo "API Error [" . $e->getErrorCode() . "]: " . $e->getMessage() . "\n";
} catch (Exception $e) {
echo "System Error: " . $e->getMessage() . "\n";
}
4. Error Handling Example
try{
// API call code
} catch (ApiException $e) {
echo "API Error [" . $e->getErrorCode() . "]: " . $e->getMessage() . "\n";
} catch (Exception $e) {
echo "System Error: " . $e->getMessage() . "\n";
}
Java SDK
Java Language SDK
1. 下载 Java SDK
在使用SmartCheapIP Java客户端之前,你需要先下载Java SDK。点击下载
系统要求:Java 8或更高版本
2. 初始化客户端
package com.proxyclient.client.example;
import com.proxyclient.client.ProxyClient;
import com.proxyclient.client.ApiException;
import com.proxyclient.client.model.FlowAccountInfo;
import com.proxyclient.client.model.PackageInfo;
import com.proxyclient.client.model.FlowDetailInfo;
// 配置客户端
ProxyClient.Config config = new ProxyClient.Config("your_apikey_here")
.setTimeout(30000);
// 创建客户端
ProxyClient client = new ProxyClient(config);
3. 完整使用示例
package com.proxyclient.client.example;
import com.proxyclient.client.ProxyClient;
import com.proxyclient.client.ApiException;
import com.proxyclient.client.model.FlowAccountInfo;
import com.proxyclient.client.model.PackageInfo;
import com.proxyclient.client.model.FlowDetailInfo;
import java.util.List;
public class ExampleUsage {
public static void main(String[] args) {
// 配置客户端
ProxyClient.Config config = new ProxyClient.Config("your_apikey_here")
.setTimeout(30000);
try {
// 创建客户端
ProxyClient client = new ProxyClient(config);
System.out.println("=== proxyclient Java Client Examples ===");
// 示例1: 创建流量线路
System.out.println("\n1. 创建流量线路...");
try {
List<FlowAccountInfo> accounts = client.createAccount("US", 60);
System.out.println("创建成功,账户数量: " + accounts.size());
for (FlowAccountInfo account : accounts) {
System.out.println("账户: " + account.getAccount() +
", 国家: " + account.getCountry() +
", 代理IP: " + account.getProxyIp() + ":" + account.getS5Port());
}
} catch (ApiException e) {
System.out.println("创建账户失败: " + e.getMessage());
}
// 示例2: 获取流量线路列表
System.out.println("\n2. 获取流量线路列表...");
try {
List<FlowAccountInfo> accountList = client.getAccountList("US", 0, 10);
System.out.println("获取到 " + accountList.size() + " 个账户");
for (FlowAccountInfo account : accountList) {
System.out.println("账户ID: " + account.getAccountId() +
", 账号: " + account.getAccount() +
", 国家: " + account.getCountry());
}
} catch (ApiException e) {
System.out.println("获取账户列表失败: " + e.getMessage());
}
// 示例3: 获取套餐信息
System.out.println("\n3. 获取套餐信息...");
try {
PackageInfo packageInfo = client.getPackageInfo();
System.out.println("总流量: " + packageInfo.getTrafficTotal() + " " + packageInfo.getUnit());
System.out.println("已使用: " + packageInfo.getTrafficUsed() + " " + packageInfo.getUnit());
System.out.println("剩余流量: " + packageInfo.getTrafficRemain() + " " + packageInfo.getUnit());
System.out.println("账户数量: " + packageInfo.getFlowAccountCount());
} catch (ApiException e) {
System.out.println("获取套餐信息失败: " + e.getMessage());
}
// 示例4: 查询流量明细
System.out.println("\n4. 查询流量明细...");
try {
List<FlowDetailInfo> trafficDetails = client.getTrafficDetail(
"", // 空字符串表示查询全部账户
"2025-11-01 00:00:00",
"2025-11-30 23:59:59"
);
System.out.println("查询到 " + trafficDetails.size() + " 条流量记录");
for (int i = 0; i < Math.min(trafficDetails.size(), 3); i++) { // 只显示前3条
FlowDetailInfo detail = trafficDetails.get(i);
System.out.println("日期: " + detail.getDate() +
", 账户: " + detail.getAccount() +
", 流量: " + detail.getTraffic());
}
} catch (ApiException e) {
System.out.println("查询流量明细失败: " + e.getMessage());
}
System.out.println("\n=== 示例执行完成 ===");
} catch (ApiException e) {
System.err.println("客户端初始化失败: " . e.getMessage());
}
}
}
4. 错误处理示例
try{
// API调用代码
} catch (ApiException e) {
System.out.println(e.getMessage());
}
1. Download Java SDK
Before using the SmartCheapIP Java client, you need to download the Java SDK. click to download
System Requirements: Java 8 or higher
2. Initialize Client
package com.proxyclient.client.example;
import com.proxyclient.client.ProxyClient;
import com.proxyclient.client.ApiException;
import com.proxyclient.client.model.FlowAccountInfo;
import com.proxyclient.client.model.PackageInfo;
import com.proxyclient.client.model.FlowDetailInfo;
// Configure client
ProxyClient.Config config = new ProxyClient.Config("your_apikey_here")
.setTimeout(30000);
// Create client
ProxyClient client = new ProxyClient(config);
3. Complete Usage Example
package com.proxyclient.client.example;
import com.proxyclient.client.ProxyClient;
import com.proxyclient.client.ApiException;
import com.proxyclient.client.model.FlowAccountInfo;
import com.proxyclient.client.model.PackageInfo;
import com.proxyclient.client.model.FlowDetailInfo;
import java.util.List;
public class ExampleUsage {
public static void main(String[] args) {
// Configure client
ProxyClient.Config config = new ProxyClient.Config("your_apikey_here")
.setTimeout(30000);
try {
// Create client
ProxyClient client = new ProxyClient(config);
System.out.println("=== ProxyClient Java Client Examples ===");
// Example 1: Create flow line
System.out.println("\n1. Creating flow line...");
try {
List<FlowAccountInfo> accounts = client.createAccount("US", 60);
System.out.println("Created successfully, account count: " + accounts.size());
for (FlowAccountInfo account : accounts) {
System.out.println("Account: " + account.getAccount() +
", Country: " + account.getCountry() +
", Proxy IP: " + account.getProxyIp() + ":" + account.getS5Port());
}
} catch (ApiException e) {
System.out.println("Failed to create account: " + e.getMessage());
}
// Example 2: Get flow line list
System.out.println("\n2. Getting flow line list...");
try {
List<FlowAccountInfo> accountList = client.getAccountList("US", 0, 10);
System.out.println("Got " + accountList.size() + " accounts");
for (FlowAccountInfo account : accountList) {
System.out.println("Account ID: " + account.getAccountId() +
", Account: " + account.getAccount() +
", Country: " + account.getCountry());
}
} catch (ApiException e) {
System.out.println("Failed to get account list: " + e.getMessage());
}
// Example 3: Get package info
System.out.println("\n3. Getting package info...");
try {
PackageInfo packageInfo = client.getPackageInfo();
System.out.println("Total traffic: " + packageInfo.getTrafficTotal() + " " + packageInfo.getUnit());
System.out.println("Used: " + packageInfo.getTrafficUsed() + " " + packageInfo.getUnit());
System.out.println("Remaining traffic: " + packageInfo.getTrafficRemain() + " " + packageInfo.getUnit());
System.out.println("Account count: " + packageInfo.getFlowAccountCount());
} catch (ApiException e) {
System.out.println("Failed to get package info: " + e.getMessage());
}
// Example 4: Query traffic details
System.out.println("\n4. Querying traffic details...");
try {
List<FlowDetailInfo> trafficDetails = client.getTrafficDetail(
"", // Empty string means query all accounts
"2025-11-01 00:00:00",
"2025-11-30 23:59:59"
);
System.out.println("Found " + trafficDetails.size() + " traffic records");
for (int i = 0; i < Math.min(trafficDetails.size(), 3); i++) { // Only show first 3
FlowDetailInfo detail = trafficDetails.get(i);
System.out.println("Date: " + detail.getDate() +
", Account: " + detail.getAccount() +
", Traffic: " + detail.getTraffic());
}
} catch (ApiException e) {
System.out.println("Failed to query traffic details: " + e.getMessage());
}
System.out.println("\n=== Example execution completed ===");
} catch (ApiException e) {
System.err.println("Client initialization failed: " . e.getMessage());
}
}
}
4. Error Handling Example
try{
// API call code
} catch (ApiException e) {
System.out.println(e.getMessage());
}
JavaScript SDK
JavaScript Language SDK
1. 下载Node.js SDK
在使用SmartCheapIP Node.js客户端之前,需要先安装SDK。点击下载
系统要求:Node.js 14或更高版本。
2. 初始化客户端
const { ProxyClient, Config, ApiError } = require('../src');
// 配置客户端
const config = new Config({
apiKey: "your_apikey_here",
timeout: 30000
});
// 创建客户端
const client = new ProxyClient(config);
3. 完整使用示例
const { ProxyClient, Config, ApiError } = require('../src');
/**
* 使用示例
*/
async function main() {
// 配置客户端
const config = new Config({
apiKey: "your_apikey_here",
timeout: 30000
});
try {
// 创建客户端
const client = new ProxyClient(config);
console.log("=== ProxyClient Node.js Client Examples ===");
// 示例1: 创建流量线路
console.log("\n1. 创建流量线路...");
try {
const accounts = await client.createAccount("US", 60);
console.log(`创建成功,账户数量: ${accounts.length}`);
accounts.forEach(account => {
console.log(`账户: ${account.account}, 国家: ${account.country}, 代理IP: ${account.proxy_ip}:${account.s5_port}`);
});
} catch (error) {
console.log(`创建账户失败: ${error.message}`);
}
// 示例2: 获取流量线路列表
console.log("\n2. 获取流量线路列表...");
try {
const accountList = await client.getAccountList("US", 0, 10);
console.log(`获取到 ${accountList.length} 个账户`);
accountList.forEach(account => {
console.log(`账户ID: ${account.account_id}, 账号: ${account.account}, 国家: ${account.country}`);
});
} catch (error) {
console.log(`获取账户列表失败: ${error.message}`);
}
// 示例3: 获取套餐信息
console.log("\n3. 获取套餐信息...");
try {
const packageInfo = await client.getPackageInfo();
console.log(`总流量: ${packageInfo.traffic_total} ${packageInfo.unit}`);
console.log(`已使用: ${packageInfo.traffic_used} ${packageInfo.unit}`);
console.log(`剩余流量: ${packageInfo.traffic_remain} ${packageInfo.unit}`);
console.log(`账户数量: ${packageInfo.flow_account_count}`);
} catch (error) {
console.log(`获取套餐信息失败: ${error.message}`);
}
// 示例4: 查询流量明细
console.log("\n4. 查询流量明细...");
try {
const trafficDetails = await client.getTrafficDetail(
"", // 空字符串表示查询全部账户
"2025-11-01 00:00:00",
"2025-11-30 23:59:59"
);
console.log(`查询到 ${trafficDetails.length} 条流量记录`);
trafficDetails.slice(0, 3).forEach(detail => { // 只显示前3条
console.log(`日期: ${detail.date}, 账户: ${detail.account}, 流量: ${detail.traffic}`);
});
} catch (error) {
console.log(`查询流量明细失败: ${error.message}`);
}
// 示例5: 删除流量线路
console.log("\n5. 删除流量线路...");
try {
const result = await client.removeAccount("test_account_123");
console.log(`删除结果: ${result ? "成功" : "失败"}`);
} catch (error) {
console.log(`删除账户失败: ${error.message}`);
}
} catch (error) {
if (error instanceof ApiError) {
console.error(`API错误 [${error.code}]: ${error.message}`);
} else {
console.error(`系统错误: ${error.message}`);
}
}
}
/**
* 错误处理示例
*/
async function handleApiError() {
const config = new Config({
apiKey: "invalid_key", // 使用无效的API密钥测试错误处理
});
try {
const client = new ProxyClient(config);
await client.getPackageInfo();
} catch (error) {
if (error instanceof ApiError) {
console.log(`API业务错误: 代码=${error.code}, 消息=${error.message}`);
} else {
console.log(`网络或其他错误: ${error.message}`);
}
}
}
// 运行示例
if (require.main === module) {
main().catch(console.error);
}
module.exports = {
main,
handleApiError
};
4. 错误处理示例
try {
const client = new ProxyClient(config);
} catch (error) {
if (error instanceof ApiError) {
console.log(`API业务错误: 代码=${error.code}, 消息=${error.message}`);
} else {
console.log(`网络或其他错误: ${error.message}`);
}
}
1. download Node.js SDK
Before using the SmartCheapIP Node.js client, you need to download the SDK first. click to download
System Requirements:Node.js 14 or higher。
2. Initialize Client
const { ProxyClient, Config, ApiError } = require('../src');
// Configure client
const config = new Config({
apiKey: "your_apikey_here",
timeout: 30000
});
// Create client
const client = new ProxyClient(config);
3. Complete Usage Example
const { ProxyClient, Config, ApiError } = require('../src');
/**
* Usage Example
*/
async function main() {
// Configure client
const config = new Config({
apiKey: "your_apikey_here",
timeout: 30000
});
try {
// Create client
const client = new ProxyClient(config);
console.log("=== ProxyClient Node.js Client Examples ===");
// Example 1: Create flow line
console.log("\n1. Creating flow line...");
try {
const accounts = await client.createAccount("US", 60);
console.log(`Created successfully, account count: ${accounts.length}`);
accounts.forEach(account => {
console.log(`Account: ${account.account}, Country: ${account.country}, Proxy IP: ${account.proxy_ip}:${account.s5_port}`);
});
} catch (error) {
console.log(`Failed to create account: ${error.message}`);
}
// Example 2: Get flow line list
console.log("\n2. Getting flow line list...");
try {
const accountList = await client.getAccountList("US", 0, 10);
console.log(`Got ${accountList.length} accounts`);
accountList.forEach(account => {
console.log(`Account ID: ${account.account_id}, Account: ${account.account}, Country: ${account.country}`);
});
} catch (error) {
console.log(`Failed to get account list: ${error.message}`);
}
// Example 3: Get package info
console.log("\n3. Getting package info...");
try {
const packageInfo = await client.getPackageInfo();
console.log(`Total traffic: ${packageInfo.traffic_total} ${packageInfo.unit}`);
console.log(`Used: ${packageInfo.traffic_used} ${packageInfo.unit}`);
console.log(`Remaining traffic: ${packageInfo.traffic_remain} ${packageInfo.unit}`);
console.log(`Account count: ${packageInfo.flow_account_count}`);
} catch (error) {
console.log(`Failed to get package info: ${error.message}`);
}
// Example 4: Query traffic details
console.log("\n4. Querying traffic details...");
try {
const trafficDetails = await client.getTrafficDetail(
"", // Empty string means query all accounts
"2025-11-01 00:00:00",
"2025-11-30 23:59:59"
);
console.log(`Found ${trafficDetails.length} traffic records`);
trafficDetails.slice(0, 3).forEach(detail => { // Only show first 3
console.log(`Date: ${detail.date}, Account: ${detail.account}, Traffic: ${detail.traffic}`);
});
} catch (error) {
console.log(`Failed to query traffic details: ${error.message}`);
}
// Example 5: Remove flow line
console.log("\n5. Removing flow line...");
try {
const result = await client.removeAccount("test_account_123");
console.log(`Delete result: ${result ? "Success" : "Failed"}`);
} catch (error) {
console.log(`Failed to delete account: ${error.message}`);
}
} catch (error) {
if (error instanceof ApiError) {
console.error(`API Error [${error.code}]: ${error.message}`);
} else {
console.error(`System Error: ${error.message}`);
}
}
}
/**
* Error Handling Example
*/
async function handleApiError() {
const config = new Config({
apiKey: "invalid_key", // Test error handling with invalid API key
});
try {
const client = new ProxyClient(config);
await client.getPackageInfo();
} catch (error) {
if (error instanceof ApiError) {
console.log(`API Business Error: code=${error.code}, message=${error.message}`);
} else {
console.log(`Network or other error: ${error.message}`);
}
}
}
// Run example
if (require.main === module) {
main().catch(console.error);
}
module.exports = {
main,
handleApiError
};
4. Error Handling Example
try {
const client = new ProxyClient(config);
} catch (error) {
if (error instanceof ApiError) {
console.log(`API Business Error: code=${error.code}, message=${error.message}`);
} else {
console.log(`Network or other error: ${error.message}`);
}
}