# 子用户

下面提供的链接指向一个页面，该页面详细介绍了我们系统内的“子用户”的概念。

[子用户](/cn/dai-li/huang-jia-zhu-zhai-dai-li/zi-yong-hu.md)

***

请注意，几乎每个端点都与子用户相关，除了值得注意的 **`index`** 和 **`delete`** 端点等例外情况外，将在成功调用时返回一个子用户资源。

{% code title="SubuserResource" %}

```json
{
    "id": 5,
    "hash": "01HQ5K3P97DY8EX9Y90YT1K6XA",
    "username": "subuser_231",
    "password": "asffqwv2f3w4214v",
    "traffic_available": 0.25,
    "traffic_used": 0
}
```

{% endcode %}

{% hint style="warning" %}
注意，请勿使用 **id** 字段。该字段已过时，在未来将被移除。
{% endhint %}

***

{% hint style="info" %}
当通过创建或更新的方式给子用户增加流量时，流量会从主账号中扣除。同样，当您删除子用户或从子用户中获取流量时，它将返回给主用户。
{% endhint %}

***

## 创建子用户

<mark style="color:blue;">`POST`</mark>  `/residential-subusers`

**正文参数**

<table><thead><tr><th width="142">名称</th><th width="107">类型</th><th>描述</th></tr></thead><tbody><tr><td>username</td><td>字符串</td><td>子用户的用户名</td></tr><tr><td>password</td><td>字符串</td><td>子用户的密码</td></tr><tr><td>traffic</td><td>浮点型</td><td>将分配给子用户的流量（GB）</td></tr><tr><td>limits</td><td>数组</td><td><p>可选参数，用于定义分配给子用户的限额。该结构可能由以下键值组成：daily_limit，monthly_limit，和/或 lifetime_limit。</p><pre><code>"limits": {                 
                 "daily_limit": 5000,
                 "monthly_limit": 150000,
                 "lifetime_limit": 1000000
}
</code></pre></td></tr></tbody></table>

**請求範例**

{% tabs %}
{% tab title="cURL" %}

```
curl -X POST https://resi-api.iproyal.com/v1/residential-subusers \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer <your_api_token>" \
     -d '{
           "username": "subuser123",
           "password": "securepassword",
           "traffic": 10.0
         }'
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
$api_token = '<your_api_token>';
$url = 'https://resi-api.iproyal.com/v1/residential-subusers';

$data = [
    'username' => 'subuser123',
    'password' => 'securepassword',
    'traffic' => 10.0
];

$payload = json_encode($data);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    "Authorization: Bearer $api_token"
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    echo $response;
}

curl_close($ch);
?>
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

api_token = '<your_api_token>'
url = 'https://resi-api.iproyal.com/v1/residential-subusers'

data = {
    'username': 'subuser123',
    'password': 'securepassword',
    'traffic': 10.0
}

headers = {
    'Content-Type': 'application/json',
    'Authorization': f'Bearer {api_token}'
}

response = requests.post(url, json=data, headers=headers)

print(response.text)
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const https = require('https');

const apiToken = '<your_api_token>';
const url = 'https://resi-api.iproyal.com/v1/residential-subusers';

const data = JSON.stringify({
  username: 'subuser123',
  password: 'securepassword',
  traffic: 10.0
});

const options = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${apiToken}`
  }
};

const req = https.request(url, options, (res) => {
  let data = '';

  res.on('data', (chunk) => {
    data += chunk;
  });

  res.on('end', () => {
    console.log(data);
  });
});

req.on('error', (error) => {
  console.error('Error:', error.message);
});

req.write(data);
req.end();
```

{% endtab %}

{% tab title="Java" %}

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String apiToken = "<your_api_token>";
        String url = "https://resi-api.iproyal.com/v1/residential-subusers";

        String requestBody = """
            {
                "username": "subuser123",
                "password": "securepassword",
                "traffic": 10.0
            }
        """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + apiToken)
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println(response.body());
    }
}
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"bytes"
	"encoding/json"
	"io"
	"log"
	"net/http"
	"fmt"
)

const (
	apiToken          = "<your_api_token>"
	residentialSubusersURL = "https://resi-api.iproyal.com/v1/residential-subusers"
)

func main() {
	data := map[string]interface{}{
		"username": "subuser123",
		"password": "securepassword",
		"traffic":  10.0,
	}

	jsonData, err := json.Marshal(data)
	if err != nil {
		log.Fatal("Error marshaling JSON:", err)
	}

	req, err := http.NewRequest(http.MethodPost, residentialSubusersURL, bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatal("Error creating request:", err)
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+apiToken)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal("Error making request:", err)
	}
	defer resp.Body.Close()

	responseBody, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal("Error reading response body:", err)
	}

	fmt.Println(string(responseBody))
}
```

{% endtab %}

{% tab title="C#" %}

```csharp
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string apiToken = "<your_api_token>";
        string url = "https://resi-api.iproyal.com/v1/residential-subusers";

        var data = new
        {
            username = "subuser123",
            password = "securepassword",
            traffic = 10.0
        };

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiToken}");

            var jsonData = JsonSerializer.Serialize(data);
            var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await client.PostAsync(url, content);

            string responseText = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseText);
        }
    }
}
```

{% endtab %}
{% endtabs %}

**响应示例：**

```json
{
    "id": 5,
    "hash": "02JVRQ5BF83PTW19G1SRD955J0",
    "username": "subuser123",
    "password": "securepassword",
    "traffic_available": 10,
    "traffic_used": 0
}
```

## 获取子用户

<mark style="color:green;">`GET`</mark>  `/residential-subusers/{ hash }`

**查询参数**

<table><thead><tr><th width="234">名称</th><th width="246">类型</th><th>描述</th></tr></thead><tbody><tr><td><code>hash</code></td><td>字符串</td><td>子用户的哈希值</td></tr></tbody></table>

**請求範例**

{% tabs %}
{% tab title="cURL" %}

```
curl -X GET "https://resi-api.iproyal.com/v1/residential-subusers/<subuser_hash>" \
     -H "Authorization: Bearer <your_api_token>"
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
$api_token = '<your_api_token>';
$url = "https://resi-api.iproyal.com/v1/residential-subusers/{hash}";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $api_token"
]);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    echo $response;
}

curl_close($ch);
?>
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

api_token = '<your_api_token>'
hash = '<subuser_hash>'
url = f'https://resi-api.iproyal.com/v1/residential-subusers/{hash}'

headers = {
    'Authorization': f'Bearer {api_token}'
}

response = requests.get(url, headers=headers)

print(response.text)
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const https = require('https');

const api_token = '<your_api_token>';
const hash = '<subuser_hash>';
const url = `https://resi-api.iproyal.com/v1/residential-subusers/${hash}`;

const options = {
  method: 'GET',
  headers: {
    'Authorization': `Bearer ${api_token}`
  }
};

const req = https.request(url, options, (res) => {
  let data = '';

  res.on('data', (chunk) => {
    data += chunk;
  });

  res.on('end', () => {
    console.log(data);
  });
});

req.on('error', (error) => {
  console.error('Error:', error.message);
});

req.end();

```

{% endtab %}

{% tab title="Java" %}

```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ApiRequest {
    public static void main(String[] args) {
        String apiToken = "<your_api_token>";
        String subuserHash = "<subuser_hash>";
        String urlString = String.format("https://resi-api.iproyal.com/v1/residential-subusers/%s", subuserHash);

        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Authorization", "Bearer " + apiToken);

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }
                in.close();

                System.out.println(content.toString());
            } else {
                System.out.println("GET request failed. Response Code: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"io"
	"log"
	"net/http"
	"fmt"
)

const (
	apiToken = "<your_api_token>"
	subuserHash = "<subuser_hash>"
)

func main() {
	url := fmt.Sprintf("https://resi-api.iproyal.com/v1/residential-subusers/%s", subuserHash)

	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		log.Fatal("Error creating request:", err)
	}

	req.Header.Set("Authorization", "Bearer "+apiToken)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal("Error making request:", err)
	}
	defer resp.Body.Close()

	responseBody, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal("Error reading response body:", err)
	}

	fmt.Println(string(responseBody))
}
```

{% endtab %}

{% tab title="C#" %}

```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string apiToken = "<your_api_token>";
        string hash = "<subuser_hash>";
        string url = $"https://resi-api.iproyal.com/v1/residential-subusers/{hash}";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiToken}");

            HttpResponseMessage response = await client.GetAsync(url);

            string responseText = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseText);
        }
    }
}
```

{% endtab %}
{% endtabs %}

**响应示例：**

```json
{
    "id": 5,
    "hash": "02JVRQ5BF83PTW19G1SRD955J0",
    "username": "subuser123",
    "password": "securepassword",
    "traffic_available": 10,
    "traffic_used": 0
}
```

## 获取多个子用户

<mark style="color:green;">`GET`</mark>  `/residential-subusers`

**查询参数**

<table><thead><tr><th width="134">名称</th><th width="104">类型</th><th>描述</th></tr></thead><tbody><tr><td>page</td><td>整型</td><td>页码</td></tr><tr><td>per_page</td><td>整型</td><td>每页的子用户数</td></tr><tr><td>search</td><td>字符串</td><td>搜索将被用来筛选用户的用户名</td></tr></tbody></table>

**請求範例**

{% tabs %}
{% tab title="cURL" %}

```
curl -X GET "https://resi-api.iproyal.com/v1/residential-subusers?page=1&per_page=10&search=username_search" \
     -H "Authorization: Bearer <your_api_token>"
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
$api_token = '<your_api_token>';
$page = 1;
$per_page = 10;
$search = 'username_search';

$url = "https://resi-api.iproyal.com/v1/residential-subusers?page=$page&per_page=$per_page&search=$search";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $api_token"
]);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    echo $response;
}

curl_close($ch);
?>
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

api_token = '<your_api_token>'
page = 1
per_page = 10
search = 'username_search'

url = f'https://resi-api.iproyal.com/v1/residential-subusers?page={page}&per_page={per_page}&search={search}'

headers = {
    'Authorization': f'Bearer {api_token}'
}

response = requests.get(url, headers=headers)

print(response.text)
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const https = require('https');

const api_token = '<your_api_token>';
const page = 1;
const per_page = 10;
const search = 'username_search';

const url = `https://resi-api.iproyal.com/v1/residential-subusers?page=${page}&per_page=${per_page}&search=${search}`;

const options = {
  method: 'GET',
  headers: {
    'Authorization': `Bearer ${api_token}`
  }
};

const req = https.request(url, options, (res) => {
  let data = '';

  res.on('data', (chunk) => {
    data += chunk;
  });

  res.on('end', () => {
    console.log(data);
  });
});

req.on('error', (error) => {
  console.error('Error:', error.message);
});

req.end();
```

{% endtab %}

{% tab title="Java" %}

```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ApiRequest {
    public static void main(String[] args) {
        String apiToken = "<your_api_token>";
        int page = 1;
        int perPage = 10;
        String search = "username_search";

        String urlString = String.format(
            "https://resi-api.iproyal.com/v1/residential-subusers?page=%d&per_page=%d&search=%s", 
            page, perPage, search
        );

        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Authorization", "Bearer " + apiToken);

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }
                in.close();

                System.out.println(content.toString());
            } else {
                System.out.println("GET request failed. Response Code: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
)

const (
	apiToken = "<your_api_token>"
	page     = 1
	perPage  = 10
	search   = "username_search"
)

func main() {
	url := fmt.Sprintf("https://resi-api.iproyal.com/v1/residential-subusers?page=%d&per_page=%d&search=%s", page, perPage, search)

	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		log.Fatal("Error creating request:", err)
	}

	req.Header.Set("Authorization", "Bearer "+apiToken)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal("Error making request:", err)
	}
	defer resp.Body.Close()

	responseBody, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal("Error reading response body:", err)
	}

	fmt.Println(string(responseBody))
}
```

{% endtab %}

{% tab title="C#" %}

```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string apiToken = "<your_api_token>";
        int page = 1;
        int perPage = 10;
        string search = "username_search";
        string url = $"https://resi-api.iproyal.com/v1/residential-subusers?page={page}&per_page={perPage}&search={search}";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiToken}");

            HttpResponseMessage response = await client.GetAsync(url);

            string responseText = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseText);
        }
    }
}
```

{% endtab %}
{% endtabs %}

**响应示例：**

```json
{
    "data": [
        {
            "id": 5,
            "hash": "02JVRQ5BF83PTW19G1SRD955J0",
            "username": "subuser123",
            "password": "securepassword",
            "traffic_available": 10,
            "traffic_used": 0
        }
    ],
    "meta": {
        "current_page": 1,
        "from": 1,
        "last_page": 1,
        "path": "https://resi-api.iproyal.com/v1/residential-subusers",
        "per_page": 20,
        "to": 1,
        "total": 1
    }
}
```

## 更新子用户

<mark style="color:orange;">`UPDATE`</mark>  `/residential-subusers/{ hash }`

**查询参数**

<table><thead><tr><th width="139">名称</th><th width="104">类型</th><th>描述</th></tr></thead><tbody><tr><td>哈希</td><td>字符串</td><td>子用户的哈希值</td></tr></tbody></table>

**正文参数**

<table><thead><tr><th width="142">名称</th><th width="107">类型</th><th>描述</th></tr></thead><tbody><tr><td>username</td><td>字符串</td><td>子用户的用户名</td></tr><tr><td>password</td><td>字符串</td><td>子用户的密码</td></tr><tr><td>traffic</td><td>浮点型</td><td>将分配给子用户的流量（GB）</td></tr><tr><td>limits</td><td>数组</td><td><p>可选参数，用于定义分配给子用户的限额。该结构可能由以下键值组成：daily_limit，monthly_limit，和/或 lifetime_limit。</p><pre><code>"limits": {                 
                 "daily_limit": 5000,
                 "monthly_limit": 150000,
                 "lifetime_limit": 1000000
}
</code></pre></td></tr></tbody></table>

**請求範例**

{% tabs %}
{% tab title="cURL" %}

```
curl -X PUT "https://resi-api.iproyal.com/v1/residential-subusers/<subuser_hash>" \
     -H "Authorization: Bearer <your_api_token>" \
     -H "Content-Type: application/json" \
     -d '{
           "username": "new_username",
           "password": "new_password",
           "traffic": 5.0
         }'
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
$api_token = '<your_api_token>';
$hash = '<subuser_hash>';
$username = 'new_username';
$password = 'new_password';
$traffic = 5.0;

$url = "https://resi-api.iproyal.com/v1/residential-subusers/$hash";

$data = [
    'username' => $username,
    'password' => $password,
    'traffic' => $traffic
];

$options = [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => 'UPDATE',
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer $api_token",
        'Content-Type: application/json'
    ],
    CURLOPT_POSTFIELDS => json_encode($data)
];

$ch = curl_init();
curl_setopt_array($ch, $options);
$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    echo $response;
}

curl_close($ch);
?>
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

api_token = '<your_api_token>'
hash = '<subuser_hash>'
url = f'https://resi-api.iproyal.com/v1/residential-subusers/{hash}'

data = {
    'username': 'new_username',
    'password': 'new_password',
    'traffic': 5.0
}

headers = {
    'Authorization': f'Bearer {api_token}',
    'Content-Type': 'application/json'
}

response = requests.put(url, json=data, headers=headers)

print(response.text)
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const https = require('https');

const api_token = '<your_api_token>';
const hash = '<subuser_hash>';
const data = JSON.stringify({
  username: 'new_username',
  password: 'new_password',
  traffic: 5.0
});

const options = {
  hostname: 'resi-api.iproyal.com',
  path: `/v1/residential-subusers/${hash}`,
  method: 'UPDATE',
  headers: {
    'Authorization': `Bearer ${api_token}`,
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
};

const req = https.request(options, (res) => {
  let responseData = '';

  res.on('data', (chunk) => {
    responseData += chunk;
  });

  res.on('end', () => {
    console.log(responseData);
  });
});

req.on('error', (error) => {
  console.error('Error:', error.message);
});

req.write(data);
req.end();
```

{% endtab %}

{% tab title="Java" %}

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String apiToken = "<your_api_token>";
        String subuserHash = "<subuser_hash>";
        String url = "https://resi-api.iproyal.com/v1/residential-subusers/" + subuserHash;

        String requestBody = """
            {
                "username": "new_username",
                "password": "new_password",
                "traffic": 5.0
            }
        """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + apiToken)
                .PUT(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println(response.body());
    }
}
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
)

const (
	apiToken    = "<your_api_token>"
	subuserHash = "<subuser_hash>"
)

func main() {
	url := fmt.Sprintf("https://resi-api.iproyal.com/v1/residential-subusers/%s", subuserHash)

	data := map[string]interface{}{
		"username": "new_username",
		"password": "new_password",
		"traffic":  5.0,
	}

	jsonData, err := json.Marshal(data)
	if err != nil {
		log.Fatal("Error marshaling JSON:", err)
	}

	req, err := http.NewRequest(http.MethodPut, url, bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatal("Error creating request:", err)
	}

	req.Header.Set("Authorization", "Bearer "+apiToken)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal("Error making request:", err)
	}
	defer resp.Body.Close()

	responseBody, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal("Error reading response body:", err)
	}

	fmt.Println(string(responseBody))
}
```

{% endtab %}

{% tab title="C#" %}

```csharp
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string apiToken = "<your_api_token>";
        string hash = "<subuser_hash>";
        string url = $"https://resi-api.iproyal.com/v1/residential-subusers/{hash}";

        var data = new
        {
            username = "new_username",
            password = "new_password",
            traffic = 5.0
        };

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiToken}");
            var jsonData = JsonSerializer.Serialize(data);
            var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await client.PutAsync(url, content);

            string responseText = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseText);
        }
    }
}
```

{% endtab %}
{% endtabs %}

**响应示例：**

```json
{
    "id": 5,
    "hash": "02JVRQ5BF83PTW19G1SRD955J0",
    "username": "new_username",
    "password": "new_password",
    "traffic_available": 5,
    "traffic_used": 0
}
```

## 刪除子用戶

<mark style="color:red;">`DELETE`</mark>  `/residential-subusers/{ hash }`

**查询参数**

<table><thead><tr><th width="234">名称</th><th width="246">类型</th><th>描述</th></tr></thead><tbody><tr><td><code>hash</code></td><td>字符串</td><td>子用户的哈希值</td></tr></tbody></table>

**請求範例**

{% tabs %}
{% tab title="cURL" %}

```
curl -X DELETE "https://resi-api.iproyal.com/v1/residential-subusers/<subuser_hash>" \
     -H "Authorization: Bearer <your_api_token>" \
     -H "Content-Type: application/json"
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
$api_token = '<your_api_token>';
$hash = '<subuser_hash>';

$url = "https://resi-api.iproyal.com/v1/residential-subusers/$hash";

$options = [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => 'DELETE',
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer $api_token",
        'Content-Type: application/json'
    ]
];

$ch = curl_init();
curl_setopt_array($ch, $options);
$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    echo $response;
}

curl_close($ch);
?>
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

api_token = '<your_api_token>'
hash = '<subuser_hash>'
url = f'https://resi-api.iproyal.com/v1/residential-subusers/{hash}'

headers = {
    'Authorization': f'Bearer {api_token}',
    'Content-Type': 'application/json'
}

response = requests.delete(url, headers=headers)

print(response.status_code)
print(response.text)
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const https = require('https');

const api_token = '<your_api_token>';
const hash = '<subuser_hash>';

const options = {
  hostname: 'resi-api.iproyal.com',
  path: `/v1/residential-subusers/${hash}`,
  method: 'DELETE',
  headers: {
    'Authorization': `Bearer ${api_token}`,
    'Content-Type': 'application/json'
  }
};

const req = https.request(options, (res) => {
  let responseData = '';

  res.on('data', (chunk) => {
    responseData += chunk;
  });

  res.on('end', () => {
    console.log(responseData);
  });
});

req.on('error', (error) => {
  console.error('Error:', error.message);
});

req.end();curl -X DELETE "https://resi-api.iproyal.com/v1/residential-subusers/<subuser_hash>" \
     -H "Authorization: Bearer <your_api_token>" \
     -H "Content-Type: application/json"
```

{% endtab %}

{% tab title="Java" %}

```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ApiRequest {
    public static void main(String[] args) {
        String apiToken = "<your_api_token>";
        String subuserHash = "<subuser_hash>";
        String urlString = String.format("https://resi-api.iproyal.com/v1/residential-subusers/%s", subuserHash);

        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("DELETE");
            connection.setRequestProperty("Authorization", "Bearer " + apiToken);
            connection.setRequestProperty("Content-Type", "application/json");

            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }
                in.close();

                System.out.println("Response Body: " + content.toString());
            } else {
                System.out.println("DELETE request failed. Response Code: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"fmt"
	"log"
	"net/http"
)

const (
	apiToken    = "<your_api_token>"
	subuserHash = "<subuser_hash>"
)

func main() {
	url := fmt.Sprintf("https://resi-api.iproyal.com/v1/residential-subusers/%s", subuserHash)

	req, err := http.NewRequest(http.MethodDelete, url, nil)
	if err != nil {
		log.Fatal("Error creating request:", err)
	}

	req.Header.Set("Authorization", "Bearer "+apiToken)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal("Error making request:", err)
	}
	defer resp.Body.Close()

	fmt.Println("Status Code:", resp.StatusCode)

	responseBody := new(bytes.Buffer)
	_, err = responseBody.ReadFrom(resp.Body)
	if err != nil {
		log.Fatal("Error reading response body:", err)
	}

	fmt.Println(responseBody.String())
}
```

{% endtab %}

{% tab title="C#" %}

```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string apiToken = "<your_api_token>";
        string hash = "<subuser_hash>";
        string url = $"https://resi-api.iproyal.com/v1/residential-subusers/{hash}";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiToken}");

            HttpResponseMessage response = await client.DeleteAsync(url);

            Console.WriteLine((int)response.StatusCode);
            string responseText = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseText);
        }
    }
}
```

{% endtab %}
{% endtabs %}

## 新增流量至子使用者

<mark style="color:blue;">`POST`</mark>  `/residential-subusers/{ hash }/give-traffic`

**查询参数**

<table><thead><tr><th width="234">名称</th><th width="246">类型</th><th>描述</th></tr></thead><tbody><tr><td><code>hash</code></td><td>字符串</td><td>子用户的哈希值</td></tr></tbody></table>

**正文参数**

<table><thead><tr><th width="142">名称</th><th width="107">类型</th><th>描述</th></tr></thead><tbody><tr><td>amount</td><td>浮点型</td><td>给予的流量（GB）</td></tr></tbody></table>

**請求範例**

{% tabs %}
{% tab title="cURL" %}

```
curl -X POST "https://resi-api.iproyal.com/v1/residential-subusers/<subuser_hash>/give-traffic" \
     -H "Authorization: Bearer <your_api_token>" \
     -H "Content-Type: application/json" \
     -d '{
           "amount": 5.0
         }'
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
$api_token = '<your_api_token>';
$hash = '<subuser_hash>';
$amount = 5.0;

$url = "https://resi-api.iproyal.com/v1/residential-subusers/$hash/give-traffic";

$data = [
    'amount' => $amount
];

$options = [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer $api_token",
        'Content-Type: application/json'
    ],
    CURLOPT_POSTFIELDS => json_encode($data)
];

$ch = curl_init();
curl_setopt_array($ch, $options);
$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    echo $response;
}

curl_close($ch);
?>
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

api_token = '<your_api_token>'
hash = '<subuser_hash>'
url = f'https://resi-api.iproyal.com/v1/residential-subusers/{hash}/give-traffic'

data = {
    'amount': 5.0
}

headers = {
    'Authorization': f'Bearer {api_token}',
    'Content-Type': 'application/json'
}

response = requests.post(url, json=data, headers=headers)

print(response.status_code)
print(response.text)
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const https = require('https');

const api_token = '<your_api_token>';
const hash = '<subuser_hash>';
const amount = 5.0;
const data = JSON.stringify({ amount });

const options = {
  hostname: 'resi-api.iproyal.com',
  path: `/v1/residential-subusers/${hash}/give-traffic`,
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${api_token}`,
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
};

const req = https.request(options, (res) => {
  let responseData = '';

  res.on('data', (chunk) => {
    responseData += chunk;
  });

  res.on('end', () => {
    console.log(responseData);
  });
});

req.on('error', (error) => {
  console.error('Error:', error.message);
});

req.write(data);
req.end();
```

{% endtab %}

{% tab title="Java" %}

```java
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ApiRequest {
    public static void main(String[] args) {
        String apiToken = "<your_api_token>";
        String subuserHash = "<subuser_hash>";
        String urlString = String.format("https://resi-api.iproyal.com/v1/residential-subusers/%s/give-traffic", subuserHash);

        String jsonData = String.format("{\"amount\": %s}", 5.0);

        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", "Bearer " + apiToken);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            OutputStream os = connection.getOutputStream();
            os.write(jsonData.getBytes());
            os.flush();
            os.close();

            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }
                in.close();

                System.out.println("Response Body: " + content.toString());
            } else {
                System.out.println("POST request failed. Response Code: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
)

const (
	apiToken    = "<your_api_token>"
	subuserHash = "<subuser_hash>"
)

func main() {
	url := fmt.Sprintf("https://resi-api.iproyal.com/v1/residential-subusers/%s/give-traffic", subuserHash)

	data := map[string]interface{}{
		"amount": 5.0,
	}

	jsonData, err := json.Marshal(data)
	if err != nil {
		log.Fatal("Error marshaling JSON:", err)
	}

	req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatal("Error creating request:", err)
	}

	req.Header.Set("Authorization", "Bearer "+apiToken)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal("Error making request:", err)
	}
	defer resp.Body.Close()

	fmt.Println("Status Code:", resp.StatusCode)

	responseBody, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal("Error reading response body:", err)
	}

	fmt.Println(string(responseBody))
}
```

{% endtab %}

{% tab title="C#" %}

```csharp
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string apiToken = "<your_api_token>";
        string hash = "<subuser_hash>";
        string url = $"https://resi-api.iproyal.com/v1/residential-subusers/{hash}/give-traffic";

        var data = new
        {
            amount = 5.0
        };

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiToken}");

            var jsonData = JsonSerializer.Serialize(data);
            var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await client.PostAsync(url, content);

            Console.WriteLine((int)response.StatusCode);
            string responseText = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseText);
        }
    }
}
```

{% endtab %}
{% endtabs %}

**响应示例：**

```json
{
    "id": 5,
    "hash": "02JVRQ5BF83PTW19G1SRD955J0",
    "username": "new_username",
    "password": "new_password",
    "traffic_available": 15,
    "traffic_used": 0
}
```

## 从子用户获取流量

<mark style="color:blue;">`POST`</mark>  `/residential-subusers/{ hash }/take-traffic`

**查询参数**

<table><thead><tr><th width="134">名称</th><th width="104">类型</th><th>描述</th></tr></thead><tbody><tr><td>hash</td><td>字符串</td><td>子用户的哈希值</td></tr></tbody></table>

**正文参数**

<table><thead><tr><th width="142">名称</th><th width="107">类型</th><th>描述</th></tr></thead><tbody><tr><td>量</td><td>浮点型</td><td>给予的流量（GB）</td></tr></tbody></table>

**請求範例**

{% tabs %}
{% tab title="cURL" %}

```
curl -X POST "https://resi-api.iproyal.com/v1/residential-subusers/<subuser_hash>/take-traffic" \
     -H "Authorization: Bearer <your_api_token>" \
     -H "Content-Type: application/json" \
     -d '{
           "amount": 5.0
         }'
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
$api_token = '<your_api_token>';
$hash = '<subuser_hash>';
$amount = 5.0;

$url = "https://resi-api.iproyal.com/v1/residential-subusers/$hash/take-traffic";

$data = [
    'amount' => $amount
];

$options = [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer $api_token",
        'Content-Type: application/json'
    ],
    CURLOPT_POSTFIELDS => json_encode($data)
];

$ch = curl_init();
curl_setopt_array($ch, $options);
$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    echo $response;
}

curl_close($ch);
?>
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

api_token = '<your_api_token>'
hash = '<subuser_hash>'
url = f'https://resi-api.iproyal.com/v1/residential-subusers/{hash}/take-traffic'

data = {
    'amount': 5.0
}

headers = {
    'Authorization': f'Bearer {api_token}',
    'Content-Type': 'application/json'
}

response = requests.post(url, json=data, headers=headers)

print(response.status_code)
print(response.text)
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const https = require('https');

const api_token = '<your_api_token>';
const hash = '<subuser_hash>';
const amount = 5.0;
const data = JSON.stringify({ amount });

const options = {
  hostname: 'resi-api.iproyal.com',
  path: `/v1/residential-subusers/${hash}/take-traffic`,
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${api_token}`,
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
};

const req = https.request(options, (res) => {
  let responseData = '';

  res.on('data', (chunk) => {
    responseData += chunk;
  });

  res.on('end', () => {
    console.log(responseData);
  });
});

req.on('error', (error) => {
  console.error('Error:', error.message);
});

req.write(data);
req.end();
```

{% endtab %}

{% tab title="Java" %}

```java
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ApiRequest {
    public static void main(String[] args) {
        String apiToken = "<your_api_token>";
        String subuserHash = "<subuser_hash>";
        String urlString = String.format("https://resi-api.iproyal.com/v1/residential-subusers/%s/take-traffic", subuserHash);

        String jsonData = String.format("{\"amount\": %s}", 5.0);

        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", "Bearer " + apiToken);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            OutputStream os = connection.getOutputStream();
            os.write(jsonData.getBytes());
            os.flush();
            os.close();

            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }
                in.close();

                System.out.println("Response Body: " + content.toString());
            } else {
                System.out.println("POST request failed. Response Code: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
)

const (
	apiToken    = "<your_api_token>"
	subuserHash = "<subuser_hash>"
)

func main() {
	url := fmt.Sprintf("https://resi-api.iproyal.com/v1/residential-subusers/%s/take-traffic", subuserHash)

	data := map[string]interface{}{
		"amount": 5.0,
	}

	jsonData, err := json.Marshal(data)
	if err != nil {
		log.Fatal("Error marshaling JSON:", err)
	}

	req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatal("Error creating request:", err)
	}

	req.Header.Set("Authorization", "Bearer "+apiToken)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal("Error making request:", err)
	}
	defer resp.Body.Close()

	fmt.Println("Status Code:", resp.StatusCode)

	responseBody, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal("Error reading response body:", err)
	}

	fmt.Println(string(responseBody))
}
```

{% endtab %}

{% tab title="C#" %}

```csharp
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string apiToken = "<your_api_token>";
        string hash = "<subuser_hash>";
        string url = $"https://resi-api.iproyal.com/v1/residential-subusers/{hash}/take-traffic";

        var data = new
        {
            amount = 5.0
        };

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiToken}");

            var jsonData = JsonSerializer.Serialize(data);
            var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await client.PostAsync(url, content);

            Console.WriteLine((int)response.StatusCode);
            string responseText = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseText);
        }
    }
}
```

{% endtab %}
{% endtabs %}

**响应示例：**

```json
{
    "id": 5,
    "hash": "02JVRQ5BF83PTW19G1SRD955J0",
    "username": "new_username",
    "password": "new_password",
    "traffic_available": 10,
    "traffic_used": 0
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.iproyal.com/cn/dai-li/huang-jia-zhu-zhai-dai-li/api/zi-yong-hu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
