# Check account status

{% hint style="danger" %}
**ATTENTION: New Error Response Format**\
In the near future, errors in our system will be classified as **expected** and **unexpected**. Depending on the type of error, the format of the JSON response will be changed. Please review the new formats on the [**Error Codes**](/eng/agws/error-codes.md) page. This change will be applied to all APIs in the AGWS system **except** ''[Make a payment](/eng/agws/make-a-payment.md)'.&#x20;

Click [here ](#examples-of-error-responses-before-the-changes)to view the old and new JSON error responses. Please take note of this update and ensure your system is ready for these changes, if necessary.
{% endhint %}

## Checking account status by username

<mark style="color:green;">`POST`</mark> <https://agwsapi.tarlanpayments.kz/showcase-gateway/api/v1/user/check>

**Headers**

| Name         | Value                                                   |
| ------------ | ------------------------------------------------------- |
| Content-Type | `application/json`                                      |
| X-Signature  | [Authorization hash](/eng/agws/creating-a-signature.md) |

**Body**

| Name                                              | Type   | Description                                |
| ------------------------------------------------- | ------ | ------------------------------------------ |
| `username`<mark style="color:red;">`*`</mark>     | String | User ID                                    |
| `agent`<mark style="color:red;">`*`</mark>        | String | Showcase code in the Tarlanpayments system |
| `project`<mark style="color:red;">`*`</mark>      | String | Project Code assigned to Tarlanpayments    |
| `service_code`<mark style="color:red;">`*`</mark> | String | Service ID on the showcase side            |

**Response**

| Name               | Type    | Description                                                                                                  |
| ------------------ | ------- | ------------------------------------------------------------------------------------------------------------ |
| status             | bool    | Request processing status                                                                                    |
| status\_code       | uint    | Error code                                                                                                   |
| message            | string  | Description of error                                                                                         |
| result             | Object  | The result of a query that contains information                                                              |
| -error\_code       | Integer | Error code                                                                                                   |
| -message           | String  | Error description                                                                                            |
| -account\_status   | Integer | Account status. For more information, see the [account status code](/eng/agws/account-status-codes-guide.md) |
| -amount            | Float   | Fixed Payment Amount                                                                                         |
| -upper\_commission | Float   | Upper commission                                                                                             |
| -fail\_reason      | Object  | Field Containing the [Failure Reason](/eng/agws/reason-for-operation-rejection.md)                           |
| --code             | Int     | Rejection Reason Code                                                                                        |
| --massage          | String  | Description of the Operation Rejection Reason                                                                |

## Additional Parameters (info)

he response body includes additional parameters that depend on the service category. The service type is recorded as a key within the **info** object. These parameters provide specific details related to the type of service and are dynamically included based on the service category.

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

```json
"info": {
    "parking": {
        "in_date": "2024-08-02T12:24:07+05:00",
        "left_free_time_minutes": 0,
        "sum": 118,
        "current_balance": -1,
        "zone":"1223-123",
        "coordinates": {
            "latitude":123.12,
            "longitude":123.0212
        },
        "duration":1,
        "phone":"77077777777"
    }
}
```

<table><thead><tr><th width="248">param</th><th>type</th><th>Desc</th></tr></thead><tbody><tr><td>in_date</td><td>timestamp</td><td>Parking Start Time</td></tr><tr><td>left_free_time_minutes</td><td>Float</td><td>Remaining Minutes for Exit</td></tr><tr><td>sum</td><td>Float</td><td>Parking Fee</td></tr><tr><td>current_balance</td><td>Float</td><td>Current Balance</td></tr><tr><td>zone </td><td>string</td><td>Parking zone</td></tr><tr><td>coordinates</td><td>object</td><td>Object containing coordinates</td></tr><tr><td>├latitude</td><td>float64</td><td>Latitude</td></tr><tr><td>├longitude</td><td>float64</td><td>Longitude</td></tr><tr><td>duration</td><td>uint</td><td>Duration in seconds</td></tr><tr><td>phone</td><td>string</td><td>Phone number</td></tr></tbody></table>
{% endtab %}

{% tab title="finance" %}

```json
"info": {
    "finance": {
        "phone": "7777777777",
        "contracts": [
            {
                "contract_id":"123456789",
                "contract_name":"Contract name",
                "contract_date": "03.01.2025 12:59:59",
                "client": "John Doe",
                "amount": 12.12,
                "min": 1.23,
                "max": 12.12
            },
            {
                "contract_id":"987654321",
                "contract_name":"Name Contract",
                "contract_date": "17.02.2025 23:23:39",
                "client": "Doe John",
                "amount": 1292.64,
                "min": 100.21,
                "max": 1292.64
            }
        ]
    }
}
```

<table><thead><tr><th width="287">param</th><th width="146">type</th><th>Desc</th></tr></thead><tbody><tr><td>phone</td><td>string</td><td>Customer's phone number</td></tr><tr><td>contracts</td><td>array</td><td>List of contracts</td></tr><tr><td>├contract_id</td><td>string</td><td>Unique contract identifier</td></tr><tr><td>├contract_name</td><td>string</td><td>Contract name</td></tr><tr><td>├contract_date</td><td>string</td><td>Contract date and time</td></tr><tr><td>├client</td><td>string</td><td>Client's name</td></tr><tr><td>├amount</td><td>float</td><td>Amount</td></tr><tr><td>├min</td><td>float</td><td>Minimum amount within the contract</td></tr><tr><td>├max</td><td>float</td><td>Maximum amount within the contract</td></tr></tbody></table>
{% endtab %}

{% tab title="utilities" %}

```json
"info": {
    "utilities": {
        "customer": {
            "address": "г.Алматы, ул. Пушкина д. 10008 кв. 111112"
        },
        "invoice": {
            "invoice_id": "89878766212421",
            "period_date": "2025-01",
            "formed_date": "2025-01-11 21:39:00",
            "expire_date": "2025-01-21"
        },
        "service": [
            {
                "fix_sum": 1234.32,
                "service_id": "1123",
                "service_name": "Service Name",
                "measure": "тг/кВт.сағ.",
                "fix_count": 0,
                "prev_count": 500,
                "last_count": 570,
                "debt_sum": 0,
                "debt_info": "",
                "prev_count_date": "2024-12-31",
                "last_count_date": "2025-01-25",
                "sum": 0,
                "pay_sum": 0,
                "is_counter_service": true
            },
            {
                "fix_sum": 1234.32,
                "service_id": "1123",
                "service_name": "Service Name",
                "measure": "тг/кВт.сағ.",
                "fix_count": 0,
                "prev_count": 500,
                "last_count": 570,
                "debt_sum": 0,
                "debt_info": "",
                "prev_count_date": "2024-12-31",
                "last_count_date": "2025-01-25",
                "sum": 0,
                "pay_sum": 0,
                "is_counter_service": false
            }                
        ]
    }
}
```

<table><thead><tr><th width="287">param</th><th width="132">type</th><th>Desc</th></tr></thead><tbody><tr><td>customer</td><td>object</td><td>Object with customer information</td></tr><tr><td>├address</td><td>string</td><td>Customer's address</td></tr><tr><td>invoice</td><td>object</td><td>Object with invoice details</td></tr><tr><td>├invoice_id</td><td>string</td><td>Unique invoice identifier</td></tr><tr><td>├period_date</td><td>string</td><td>Invoice period</td></tr><tr><td>├formed_date</td><td>string</td><td>Invoice creation date</td></tr><tr><td>├expire_date</td><td>string</td><td>Invoice due date</td></tr><tr><td>service</td><td>array</td><td>List of utility services</td></tr><tr><td>├fix_sum</td><td>float</td><td>Fixed service amount</td></tr><tr><td>├service_id</td><td>string</td><td>Unique service identifier</td></tr><tr><td>├service_name</td><td>string</td><td>Name of the service</td></tr><tr><td>├measure</td><td>string</td><td>Unit of measurement for the service</td></tr><tr><td>├fix_count</td><td>float</td><td>Fixed quantity</td></tr><tr><td>├prev_count</td><td>float</td><td>Previous meter reading</td></tr><tr><td>├last_count</td><td>float</td><td>Current meter reading</td></tr><tr><td>├debt_sum</td><td>float</td><td>Outstanding debt amount</td></tr><tr><td>├debt_info</td><td>string</td><td>Debt-related information</td></tr><tr><td>├prev_count_date</td><td>string</td><td>Date of the previous meter reading</td></tr><tr><td>├last_count_date</td><td>string</td><td>Date of the current meter reading</td></tr><tr><td>├sum</td><td>float</td><td>Total accrued amount</td></tr><tr><td>├pay_sum</td><td>float</td><td>Amount to be paid by client</td></tr><tr><td>├is_counter_service</td><td>bool</td><td>Indicates whether the service is metered (<code>true</code> – yes, <code>false</code> – no)</td></tr></tbody></table>
{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="200: OK Example of a successful response" %}

```json
 {
    "status": true,
    "status_code": 0,
    "message": "Success",
    "result": {
        "error_code": 0,
        "message": "This account is active",
        "account_status": 1,
        "fail_reason": {},
        "info": {
            "parking": {
                "in_date": "2024-08-02T12:24:07+05:00",
                "left_free_time_minutes": 0,
                "sum": 118,
                "current_balance": -1
            }
        },
        "amount":119,
        "upper_commission": 122
    }
}
```

{% endtab %}

{% tab title="200: OK Example of a failed response" %}

```json
 {
    "status": true,
    "status_code": 0,
    "message": "Success",
    "result": {
        "error_code": 0,
        "message": "This account is inactive",
        "account_status": 0,
        "fail_reason": {
            "code": 100,
            "message": "Unknown reason, clarification required"
        },
        "info": {
            "parking": {
                "in_date": "",
                "left_free_time_minutes": 0,
                "sum": 0,
                "current_balance": 0
            }
        }
    }
}
```

{% endtab %}
{% endtabs %}

#### Examples of error responses *before* the changes

{% tabs %}
{% tab title="404 Not Found" %}

```json
{
    "status": false,
    "status_code": 1407,
    "message": "Cache: item not found",
    "result": {}
}
```

{% endtab %}

{% tab title="400 Bad Request" %}

```json
{
    "status": false,
    "status_code": 1014,
    "message": "Invalid signature",
    "result": {}
}
```

{% endtab %}
{% endtabs %}

#### Examples of error responses *after* the changes

{% tabs %}
{% tab title="200 OK: Expected Error" %}

```json
{
    "status": true,
    "status_code": 0,
    "message": "Success",
    "result": {
        "error_code": 1407,
        "message": "Cache: item not found",
        "data": null
    }
}
```

{% endtab %}

{% tab title="400 Bad Request: Unexpected Error" %}

```json
{
    "status": false,
    "status_code": 1014,
    "message": "Invalid signature",
    "result": {}
}
```

{% endtab %}
{% endtabs %}

Account check

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

```go
package main

import (
	"bytes"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
	"sort"
)

// Response представляет ответ от сервера

// Body представляет структуру запроса
type Body struct {
	Agent       string `json:"agent"`
	UserName    string `json:"username"`
	Project     string `json:"project"`
	ServiseCode string `json:"service_code"`
}

// MakeSign генерирует подпись для HTTP-запроса
func MakeSign(body Body, secretKey string) (string, error) {
	// Конвертируем структуру в map для сортировки
	dataMap := make(map[string]interface{})
	jsonData, _ := json.Marshal(body)
	json.Unmarshal(jsonData, &dataMap)

	// Сортируем ключи по алфавиту
	keys := make([]string, 0, len(dataMap))
	for key := range dataMap {
		keys = append(keys, key)
	}
	sort.Strings(keys)

	// Создаем отсортированный JSON
	sortedData := make(map[string]interface{})
	for _, key := range keys {
		sortedData[key] = dataMap[key]
	}

	// Преобразуем отсортированные данные в JSON
	sortedJson, err := json.Marshal(sortedData)
	if err != nil {
		return "", err
	}

	// Кодируем JSON в base64
	base64EncodedData := base64.StdEncoding.EncodeToString(sortedJson)
	// Конкатенируем base64-данные с секретом
	dataToSign := base64EncodedData + secretKey

	// Хешируем SHA-256
	sha256Hash := sha256.Sum256([]byte(dataToSign))
	sign := hex.EncodeToString(sha256Hash[:])

	return sign, nil
}

// CheckLogin отправляет POST-запрос и обрабатывает ответ
func CheckLogin(body Body, url, signature string) (string, error) {
	// Конвертируем структуру в JSON для отправки
	jsonData, err := json.Marshal(body)
	if err != nil {
		return "", err
	}

	// Создаем и отправляем POST-запрос
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		return "", err
	}

	// Устанавливаем подпись запроса
	req.Header.Set("X-Signature", signature)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// Чтение и обработка ответа
	bodyBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	response := string(bodyBytes)

	// Вывод ответа и результата
	return response, nil
}

func main() {
	// URL Запроса
	RequestURL := "https://agwsapi.tarlanpayments.kz/showcase-gateway/api/v1/user/check"
	// Secret Проекта
	SecretKey := "12345"

	// Тело запроса
	requestBody := Body{
		Agent:       "agent",
		UserName:    "login",
		Project:     "project",
		ServiseCode: "servise",
	}

	// Генерация заголовка
	sign, err := MakeSign(requestBody, SecretKey)
	if err != nil {
		log.Println("Error generating signature:", err)
		return
	}

	// Отправка запроса
	Response, err := CheckLogin(requestBody, RequestURL, sign)
	if err != nil {
		log.Panic("Error sending request", err)
		return
	}

	if Response != "" {
		log.Println(Response)
	}
}

```

{% endtab %}
{% endtabs %}


---

# 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.tarlanpayments.kz/eng/agws/check-account-status.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.
