# Cancelar Suscripción

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

{% hint style="success" %}
**Producción:** <https://api.payvalida.com/v4/subscriptions>
{% endhint %}

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

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

<table data-header-hidden><thead><tr><th width="151"></th><th width="133"></th><th width="150"></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 Payválida. Se entrega con las credenciales.</td></tr><tr><td>id</td><td>string</td><td>sí</td><td>id de la suscripción que se quiere cancelar</td></tr><tr><td>checksum</td><td>string</td><td>sí</td><td><p>Cadena de comprobación con SHA512 (merchant+id+FIXED_HASH)</p><p><br></p></td></tr></tbody></table>
{% endtab %}

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

```bash
curl --location --request DELETE 'https://api-test.payvalida.com/v4/subscriptions' \
--header 'Content-Type: application/json' \
--data-raw '{
   "id":"bbc10ac0-81f2-405b-9357-97a435800e95",
   "timestamp":1686943428,
   "merchant":"kuanto",
   "checksum":"31d056705df5318578bb923cced69edeb1e38fd394ac44498363f984256a7fe0fd8563f6ca736ecc8ad12cfddd38ba870755afd594c907e0771fb368329bed2e"
}'
```

{% 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.              |
| {% endtab %} |            |        |                                           |

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

```json
{
    "CODE": "0000",
    "DESC": "OK",
}
```

{% endtab %}

{% tab title="Cabeceras" %}

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

## Ejemplos

* Go

```go
package main

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

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

	// Prepare the request payload
	payload := `{
		"id":"bbc10ac0-81f2-405b-9357-97a435800e95",
		"merchant":"kuanto",
		"checksum":"31d056705df5318578bb923cced69edeb1e38fd394ac44498363f984256a7fe0fd8563f6ca736ecc8ad12cfddd38ba870755afd594c907e0771fb368329bed2e"
	}`

	// Create a new SHA-512 hasher
	hasher := sha512.New()

	// Concatenate the values to create the checksum
	hasher.Write([]byte("kuanto"))
	hasher.Write([]byte("bbc10ac0-81f2-405b-9357-97a435800e95"))
	hasher.Write([]byte("FIXED_HASH"))
	checksum := hex.EncodeToString(hasher.Sum(nil))

	// Update the checksum value in the request payload
	payload = strings.Replace(payload, "31d056705df5318578bb923cced69edeb1e38fd394ac44498363f984256a7fe0fd8563f6ca736ecc8ad12cfddd38ba870755afd594c907e0771fb368329bed2e", checksum, 1)

	// Create an HTTP DELETE request
	req, err := http.NewRequest("DELETE", url, strings.NewReader(payload))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

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

	// Send the request and get the response
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()

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

	// Print the response body
	fmt.Println("Response Body:", string(body))
}

```

* PHP

```php
<?php

$url = 'https://api-test.payvalida.com/v4/subscriptions';

// Prepare the request payload
$payload = array(
    'id' => 'bbc10ac0-81f2-405b-9357-97a435800e95',
    'merchant' => 'kuanto',
    'checksum' => '31d056705df5318578bb923cced69edeb1e38fd394ac44498363f984256a7fe0fd8563f6ca736ecc8ad12cfddd38ba870755afd594c907e0771fb368329bed2e'
);

// Create the checksum
$data = $payload['merchant'] . $payload['id'] . 'FIXED_HASH';
$checksum = hash('sha512', $data);

// Update the checksum value in the payload
$payload['checksum'] = $checksum;

// Convert the payload to JSON
$jsonPayload = json_encode($payload);

// Create cURL resource
$ch = curl_init($url);

// Set the request method to DELETE
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');

// Set the request headers
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

// Set the request payload
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload);

// Set the option to receive the response as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Send the request and get the response
$response = curl_exec($ch);

// Close cURL resource
curl_close($ch);

// Print the response body
echo 'Response Body: ' . $response . PHP_EOL;

?>
```

* Javascript

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

const url = 'https://api-test.payvalida.com/v4/subscriptions';
const merchant = 'kuanto';
const fixedHash = 'FIXED_HASH';

const checksum = createChecksum(merchant, fixedHash);

const data = {
  id: 'bbc10ac0-81f2-405b-9357-97a435800e95',
  merchant: merchant,
  checksum: checksum
};

const payload = JSON.stringify(data);

const options = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  }
};

const req = https.request(url, options, (res) => {
  let body = '';
  
  res.on('data', (chunk) => {
    body += chunk;
  });

  res.on('end', () => {
    console.log('Response:', body);
  });
});

req.on('error', (error) => {
  console.error('Failed to send request:', error);
});

req.write(payload);
req.end();

function createChecksum(merchant, fixedHash) {
  const data = merchant + fixedHash;
  const checksum = crypto.createHash('sha512').update(data).digest('hex');

  return checksum;
}

```

* 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;
import java.time.Instant;

public class Main {

    public static void main(String[] args) {
        String url = "https://api-test.payvalida.com/v4/subscriptions";

        // Prepare the request payload
        String payload = "{\n" +
                "   \"id\":\"bbc10ac0-81f2-405b-9357-97a435800e95\",\n" +
                "   \"merchant\":\"kuanto\",\n" +
                "   \"checksum\":\"31d056705df5318578bb923cced69edeb1e38fd394ac44498363f984256a7fe0fd8563f6ca736ecc8ad12cfddd38ba870755afd594c907e0771fb368329bed2e\"\n" +
                "}";

        // Create the checksum
        String data = "kuanto" + "bbc10ac0-81f2-405b-9357-97a435800e95" + "FIXED_HASH";
        String checksum = calculateSHA512(data);

        // Update the checksum value in the payload
        payload = payload.replace("31d056705df5318578bb923cced69edeb1e38fd394ac44498363f984256a7fe0fd8563f6ca736ecc8ad12cfddd38ba870755afd594c907e0771fb368329bed2e", checksum);

        try {
            // Create the DELETE request
            URL requestUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
            connection.setRequestMethod("DELETE");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            // Set the request payload
            OutputStream outputStream = connection.getOutputStream();
            byte[] payloadBytes = payload.getBytes(StandardCharsets.UTF_8);
            outputStream.write(payloadBytes);
            outputStream.close();

            // Send the request and get the response
            int responseCode = connection.getResponseCode();

            // Read the response body
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder responseBody = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                responseBody.append(line);
            }
            reader.close();

            // Print the response body
            System.out.println("Response Body: " + responseBody.toString());

            // Close the connection
            connection.disconnect();
        } catch (IOException e) {
            System.out.println("Error sending request: " + e.getMessage());
        }
    }

    private static String calculateSHA512(String data) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-512");
            byte[] hash = digest.digest(data.getBytes(StandardCharsets.UTF_8));
            return bytesToHex(hash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }
}

```

* Python

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

url = 'https://api-test.payvalida.com/v4/subscriptions'

# Prepare the request payload
payload = {
    'id': 'bbc10ac0-81f2-405b-9357-97a435800e95',
    'merchant': 'kuanto',
    'checksum': '31d056705df5318578bb923cced69edeb1e38fd394ac44498363f984256a7fe0fd8563f6ca736ecc8ad12cfddd38ba870755afd594c907e0771fb368329bed2e'
}

# Create the checksum
data = payload['merchant'] + payload['id'] + 'FIXED_HASH'
checksum = hashlib.sha512(data.encode()).hexdigest()

# Update the checksum value in the payload
payload['checksum'] = checksum

# Send the DELETE request
headers = {'Content-Type': 'application/json'}
response = requests.delete(url, headers=headers, json=payload)

# Print the response body
print('Response Body:', response.text)

```


---

# 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/suscripciones/cancelar-suscripcion.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.
