# Checking the refill 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**](https://docs.tarlanpayments.kz/eng/agws/error-codes) page. This change will be applied to all APIs in the AGWS system **except** ''[Make a payment](https://docs.tarlanpayments.kz/eng/agws/make-a-payment)'.

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

<mark style="color:green;">`POST`</mark>[ ](https://agwsapi.tarlanpayments.kz/showcase-gateway/api/v1/action/status)`https://agwsapi.tarlanpayments.kz/showcase-gateway/api/v1/action/status`

**Headers**

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

**Body**

| Name                                            | Type   | Description                     |
| ----------------------------------------------- | ------ | ------------------------------- |
| agent<mark style="color:red;">\*</mark>         | String | Showcase code in Tarlan system  |
| project<mark style="color:red;">\*</mark>       | String | Project Code assigned by Tarlan |
| service\_code<mark style="color:red;">\*</mark> | String | Service ID on the showcase side |
| external\_id<mark style="color:red;">\*</mark>  | String | Payment ID on the showcase side |

**Response**

<table><thead><tr><th width="251">Name</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td>status</td><td>bool</td><td>Request processing status</td></tr><tr><td>status_code</td><td>uint</td><td>Error code</td></tr><tr><td>message</td><td>string</td><td>Description of error</td></tr><tr><td>result</td><td>Object</td><td>The result of a query that contains information</td></tr><tr><td>-error_code</td><td>uint</td><td>Error code</td></tr><tr><td>-message</td><td>String</td><td>Error description</td></tr><tr><td>-data</td><td>Object</td><td>Information about data</td></tr><tr><td>--status_code</td><td>String</td><td>Transaction status code</td></tr><tr><td>--status_message</td><td>String</td><td>Description of transaction status</td></tr><tr><td>--username</td><td>String</td><td>User ID</td></tr><tr><td>--amount</td><td>Float</td><td>Amount credited</td></tr><tr><td>--datetime</td><td>String</td><td>Time of payment initiation in the storefront system. ISO 8601 Current Timestamp format</td></tr><tr><td>--project</td><td>String</td><td>Project Code assigned by Tarlan</td></tr><tr><td>--fail_reason</td><td>Object</td><td>Field Containing the <a href="reason-for-operation-rejection">Failure Reason</a></td></tr><tr><td>---code</td><td>Int</td><td>Rejection Reason Code</td></tr><tr><td>---message</td><td>String</td><td>Description of the Operation Rejection Reason</td></tr><tr><td>--external_id</td><td>String</td><td>Payment ID on the showcase side</td></tr></tbody></table>

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

```json
{    
    "status": true,
    "status_code": 0,
    "message": "Success",
    "result":{
        "error_code" : 0,
        "message": "",
        "data": {
            "status_code": "2",
            "status_message": "Transaction successfully processed",
            "username": "989898",
            "amount": 100,
            "datetime": "2022-12-01T15:45:00Z",
            "project": "mobile",
            "fail_reason": {
                "code": 100,
                "message": "Unknown reason, clarification required"
            },
            "service_code": "201106",
            "external_id": "200001",
        }
}
```

{% endtab %}
{% endtabs %}

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

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

```json
{
    "status": false,
    "status_code": 1041,
    "message": "Order 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" : 1041,
        "message": "Order not found",
        "data": null
    }
}
```

{% endtab %}

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

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

{% endtab %}
{% endtabs %}

Checking the refill status

{% 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"`
	Project     string `json:"project"`
	ServiseCode string `json:"service_code"`
	ExternalID  string `json:"external_id"`
}

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

// CheckCashStatus отправляет POST-запрос и обрабатывает ответ
func CheckCashStatus(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/action/status"
	// Secret Проекта
	SecretKey := "12345"

	// Тело запроса
	requestBody := Body{
		Agent:       "agent",
		Project:     "project",
		ServiseCode: "service",
		ExternalID:  "reference_id",
	}

	// Генерация заголовка
	sign, err := MakeSign(requestBody, SecretKey)
	if err != nil {
		log.Println("Error generating signature:", err)
		return
	}
	// Отправка запроса
	Response, err := CheckCashStatus(requestBody, RequestURL, sign)
	if err != nil {
		log.Panic("Error sending request", err)
		return
	}

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

```

{% endtab %}
{% endtabs %}
