# Obtener subscripción

{% hint style="info" %}
Método: **POST**
{% endhint %}

{% hint style="success" %}
**Producción:** [https://api.payvalida.com/subscriptions/merchants/api/get/subscription](https://api-test.payvalida.com/subscriptions/merchants/api/get/subscription)
{% endhint %}

{% hint style="success" %}
**Sandbox:** <https://api-test.payvalida.com/subscriptions/merchants/api/get/subscription>
{% endhint %}

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

<table data-header-hidden data-full-width="true"><thead><tr><th width="161"></th><th width="121"></th><th></th><th></th></tr></thead><tbody><tr><td>Campo</td><td>Tipo</td><td>Requerido</td><td>Descripción</td></tr><tr><td>merchant</td><td>string</td><td>sí</td><td>Nombre asignado para el comercio en Payvalida. Se entrega con las credenciales.</td></tr><tr><td>request_id</td><td>string</td><td>sí</td><td>id de la operación de busqueda.</td></tr><tr><td>subscription_id</td><td>string</td><td>sí</td><td>id de la subscripción a buscar.<br></td></tr><tr><td>checksum</td><td>string</td><td>sí</td><td>Cadena de comprobación con SHA512 (merchant+subscription_id+request_id+ FIXED_HASH)</td></tr></tbody></table>
{% endtab %}

{% tab title="Request (ejemplo)" %}

```bash
curl --location --request POST 'https://api-test.payvalida.com/subscriptions/merchants/api/get/subscription' \
--header 'Content-Type: application/json' \
--data-raw '{
    "merchant": "kuanto",
    "subscription_id": "5c77976a-e6dc-4e58-b046-bc366740f4f7",
    "request_id": "123",
    "checksum": "57b901965399ada47ac38169759ee1c115166ec9b2aca725d5137204058b3f66b33b68ba84304752bf879d061b5568f650ed28ac4bd5272f9926fb2e763f8d17"
}'
```

{% endtab %}

{% tab title="Response" %}

| Campo        | Estructura | Tipo   | Descripción                                          |
| ------------ | ---------- | ------ | ---------------------------------------------------- |
| CODE         | -          | string | Código de respuesta **0000** para **OK.**            |
| DESC         | -          | string | Descripción de la respuesta.                         |
| DATA         | -          | string | Datos del registro                                   |
| subscription | DATA       | struct | Estructura con los datos asociados a la subscripcion |
|              |            |        |                                                      |

{% endtab %}

{% tab title="Response (ejemplo)" %}

```json
{
    "CODE": "0000",
    "DESC": "OK",
    "DATA": {
        "subscription": {
            "subscription_id": "5c77976a-e6dc-4e58-b046-bc366740f4f7",
            "created_at": "2024-11-05T19:04:34Z",
            "start_date": "05/11/2024",
            "status": "CANCELED",
            "plan": {
                "plan_id": "4093f61b-c1df-40c0-9d82-54ea8f918c3b",
                "amount": "100",
                "country": "343",
                "created_at": "2024-11-05T15:28:21Z",
                "currency": "COP",
                "description": "Prueba plan day",
                "interval": "day",
                "interval_count": "1"
            },
            "customer": {
                "customer_id": "f59d39d4-d347-4b07-b3f6-99799a5027aa",
                "first_name": "John",
                "last_name": "Doe",
                "user_di": "199999929",
                "type_di": "CC",
                "cellphone": "+573002222222",
                "email": "test@test.com",
                "credit_card_data": {}
            }
        }
    }
}
```

{% endtab %}

{% tab title="Cabeceras" %}

| Cabecera      | Valor            |
| ------------- | ---------------- |
| Content-Type  | application/json |
| {% endtab %}  |                  |
| {% endtabs %} |                  |

### Ejemplos

* Go

```go
package main

import (
	"bytes"
	"crypto/sha512"
	"encoding/hex"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

func main() {
	url := "https://api-test.payvalida.com/subscriptions/merchants/api/get/subscription"

	merchant := "kuanto"
	request_id := "month"
	subscription_id := "5c77976a-e6dc-4e58-b046-bc366740f4f7"
	fixedHash := "FIXED_HASH"

	checksum := createChecksum(merchant, subscription_id, request_id, fixedHash)

	payload := []byte(fmt.Sprintf(`{
		"merchant": "%s",
		"request_id": "%s",
		"subscription_id": "%s",
		"checksum":"%s",
	}`, merchant, request_id, subscription_id, checksum))

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}

	defer resp.Body.Close()

	// Read response body
	responseData, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return
	}

	// Print response data
	fmt.Println("Response:", string(responseData))
}

func createChecksum(merchant, subscription_id, request_id, fixedHash string) string {
	checksumData := merchant + subscription_id + request_id + fixedHash
	hash := sha512.Sum512([]byte(checksumData))
	checksum := hex.EncodeToString(hash[:])
	return checksum
}

```

* PHP

<pre class="language-php"><code class="lang-php">&#x3C;?php
$client = new Client();
$headers = [
  'Content-Type' => 'application/json'
];

$url = 'https://api-test.payvalida.com/subscriptions/merchants/api/get/subscription';
$merchant = 'kuanto';
<strong>$request_id = '123';
</strong>$subscription_id = '5c77976a-e6dc-4e58-b046-bc366740f4f7';
$fixedHash = 'FIXED_HASH';

$checksum = createChecksum($merchant, $subscription_id, $request_id, $fixedHash);

$body = '{
  "merchant": $merchant,
  "request_id": $request_id,
  "subscription_id": $subscription_id,
  "checksum": $checksum
}';
$request = new Request('POST', $url, $headers, $body);
$res = $client->sendAsync($request)->wait();
echo $res->getBody();

function createChecksum($merchant, $subscription_id, $request_id, $fixedHash)
{
    $checksumData = $merchant . $subscription_id . $request_id . $fixedHash;
    $checksum = hash('sha512', $checksumData);
    return $checksum;
}
?>
</code></pre>

* Javascript

```javascript
const fetch = require('node-fetch');
const crypto = require('crypto');

const url = 'https://api-test.payvalida.com/subscriptions/merchants/api/get/subscription';
const merchant = 'kuanto';
const request_id = 'month';
const subscription_id = '5c77976a-e6dc-4e58-b046-bc366740f4f7';
const fixedHash = 'FIXED_HASH';

const checksumData = merchant + subscription_id + request_id + fixedHash;
const checksum = crypto.createHash('sha512').update(checksumData).digest('hex');

const payload = JSON.stringify({
merchant,
request_id,
page,
sort,
checksum
});

fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: payload,
})
.then(response => response.text())
.then(body => {
console.log('Response:', body);
})
.catch(error => {
console.error('Error sending request:', error);
});
```

* Java

```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static void main(String[] args) {
        String url = "https://api-test.payvalida.com/subscriptions/merchants/api/get/subscription";
        String merchant = "kuanto";
        String request_id = "123";
        String subscription_id = "5c77976a-e6dc-4e58-b046-bc366740f4f7";
        String fixedHash = "FIXED_HASH";

        String checksum = createChecksum(merchant, subscription_id, request_id, fixedHash);

        String payload = String.format("{\"merchant\": \"%s\", \"request_id\": \"%s\", \"subscription_id\": \"%s\", \"checksum\": \"%s\"}",
                merchant, request_id, subscription_id, checksum);
        try {
            URL requestUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            try (OutputStream outputStream = connection.getOutputStream()) {
                byte[] input = payload.getBytes(StandardCharsets.UTF_8);
                outputStream.write(input, 0, input.length);
            }

            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String line;
                    StringBuilder response = new StringBuilder();
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    System.out.println("Response: " + response.toString());
                }
            } else {
                System.out.println("Error: " + responseCode);
            }

            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String createChecksum(String merchant, String subscription_id, String request_id, String fixedHash) {
        String checksumData = merchant + subscription_id + request_id + fixedHash;
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-512");
            byte[] hashBytes = digest.digest(checksumData.getBytes(StandardCharsets.UTF_8));
            StringBuilder hexString = new StringBuilder();
            for (byte hashByte : hashBytes) {
                String hex = Integer.toHexString(0xff & hashByte);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}

```

* Python

```python
import requests
import hashlib
import json
import time

url = 'https://api-test.payvalida.com/subscriptions/merchants/api/get/subscription'
merchant = 'kuanto'
request_id = '123'
page = 1
sort = 'DESC'
fixed_hash = 'FIXED_HASH'


checksum_data = merchant + request_id + fixed_hash
checksum = hashlib.sha512(checksum_data.encode()).hexdigest()

payload = {
    'merchant': merchant,
    'request_id': request_id,
    'page': page,
    'sort': sort,
    'checksum': checksum
}

headers = {
    'Content-Type': 'application/json'
}

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

if response.status_code == 200:
    print('Response:', response.text)
else:
    print('Error:', response.status_code)

```


---

# 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.payvalida.com/api-suscripciones/visualizacion-de-subscripciones/obtener-subscripcion.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.
