# Проверка остатка баланса на счету

{% hint style="danger" %}
В ближайшее время в нашей системе ошибки будут разделены на **ожидаемые** и **неожидаемые**. Это приведет к изменению формата JSON-ответа в зависимости от типа ошибки. Пожалуйста, ознакомьтесь с изменениями на странице [**Коды Ошибок**](/agws/kody-oshibok.md). Изменения будут применены ко всем API в системе AGWS, за исключением методов «[Проведение платежа](/agws/provedenie-platezha.md)».

Нажмите [здесь](#primery-otvetov-ob-oshibkakh-do-vneseniya-izmenenii), чтобы просмотреть старые и новые ответы об ошибках JSON. Обратите внимание на это обновление и убедитесь, что ваша система готова к изменениям, если это необходимо.
{% endhint %}

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

**Headers**

| Name         | Value                                                             |
| ------------ | ----------------------------------------------------------------- |
| Content-Type | `application/json`                                                |
| X-Signature  | [Авторизационный хэш](/platezhnyi-shlyuz/formirovanie-podpisi.md) |

**Body**

| Name                                    | Type   | Description                  |
| --------------------------------------- | ------ | ---------------------------- |
| agent<mark style="color:red;">\*</mark> | String | Код витрины в системе Tarlan |

**Response**

<table><thead><tr><th width="181">Name</th><th width="132">Type</th><th>Description</th></tr></thead><tbody><tr><td>status</td><td>bool</td><td>Статус обработки запроса</td></tr><tr><td>status_code</td><td>uint</td><td>Код ошибки</td></tr><tr><td>message</td><td>string</td><td>Описание ошибки</td></tr><tr><td>result</td><td>Object</td><td>Результат запроса, в котором содержится информация</td></tr><tr><td>-showcase_code</td><td>String</td><td>Код витрины в системе Tarlan</td></tr><tr><td>-balance</td><td>float</td><td>Текущий баланс</td></tr></tbody></table>

{% tabs %}
{% tab title="200: OK Пример успешного ответа" %}

```json
{
    "status": true,
    "status_code": 0,
    "message": "Success",
    "result": {
        "showcase_code": "daw",
        "balance": 0
    }
}
```

{% endtab %}
{% endtabs %}

#### Примеры ответов об ошибках *до* внесения изменений

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

```json
{
    "status": false,
    "status_code": 8015,
    "message": "account doesn't exist",
    "result": {}
}
```

{% endtab %}

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

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

{% endtab %}
{% endtabs %}

#### Примеры ответов об ошибках *после* внесения изменений

{% tabs %}
{% tab title="200 OK: Ожидаемая ошибка" %}

```json
{
    "status": true,
    "status_code": 0,
    "message": "Success",
    "result": {
        "error_code": 8015,
        "message": "account doesn't exist",
        "data": null
    }
}
```

{% endtab %}

{% tab title="400 Bad Request: Неожидаемая ошибка" %}

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

{% endtab %}
{% endtabs %}

Проверка баланса&#x20;

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

```go
package main

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

const (
	// agent - код витрины на стороне Tarlan
	agent = "agent"
	// url - URL для отправки запроса
	url = "https://agwsapi.tarlanpayments.kz/showcase-gateway/api/v1/showcase/balance"
	// secret -secret проекта
	secret = "12345"
)

// Response представляет ответ от сервера
type Response struct {
	Status     bool   `json:"status"`
	StatusCode int    `json:"status_code"`
	Message    string `json:"message"`
	Result     Result `json:"result"`
}

type Result struct {
	ShowcaseCode string  `json:"showcase_code"`
	Message      string  `json:"message"`
	Balance      float64 `json:"balance"`
}

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

// 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
}

// CheckBalance отправляет POST-запрос и обрабатывает ответ
func CheckBalance(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
	}
	jsonResponse := string(bodyBytes)

	// Структура для парсинга ответа
	var response Response
	err = json.Unmarshal([]byte(jsonResponse), &response)
	if err != nil {
		return "", err
	}

	log.Printf("Status-%v, %v", resp.StatusCode, jsonResponse)

	// Определение поля message
	var message string

	// Извлечение ответа
	if resp.StatusCode == http.StatusOK {
	if response.StatusCode == 0 {
	balance := strconv.FormatFloat(response.Result.Balance, 'f', -1, 64)
	message = "Showcase " + response.Result.ShowcaseCode + " balance is " + balance
	} else {
	message = response.Result.Message
	}
	} else {
	message = response.Message
	}

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

func main() {

	// URL Запроса
	RequestURL := url
	// Secret Проекта
	SecretKey := secret
	// Тело запроса
	requestBody := Body{
		Agent: agent,
	}

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

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

	// Вывод message из лога
	if Message != "" {
		log.Println(Message)

	}

}

```

{% 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/agws/proverka-ostatka-balansa-na-schetu.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.
