Registrar Suscripción

Permite registrar la información para generar una suscripción junto a la información del cliente

Método: POST

CampoEstructuraTipoRequeridoDescripción

merchant

string

Nombre asignado para el comercio en Payválida. Se entrega con las credenciales.

plan_id

string

id del plan que se le asignará al cliente para activar la suscripción.

start_date

string

no

Fecha de inicio de la suscripción en formato DD/MM/AAAA. Si no se proporciona, se asignará la fecha de invocación. Esta fecha corresponde al primer pago y marca el comienzo de la frecuencia de pagos de la suscripción. Si el pago es con tarjeta de credito se tomara esta fecha como la fecha de hoy.

checksum

string

Cadena de comprobación con SHA512 (merchant + plan_id + FIXED_HASH).

customer

struct

Estructura con la información de usuario a la que se le enviará la suscripción

email

customer

string

Correo electrónico del cliente. Debe cumplir con el formato estándar de correo válido.

user_di

customer

string

Número del documento de identidad del cliente.

type_di

customer

string

Tipo del documento de identidad del cliente.

first_name

customer

string

Nombre del cliente en el documento de identidad (no acepta caracteres especiales ni acentos).

last_name

customer

string

Apellido del cliente en el documento de identidad (no acepta caracteres especiales ni acentos).

cellphone

customer

string

Número de celular del cliente. Debe llevar el indicativo del país.

credit_card_data

struct

no

Estructura para activar débito automático de tarjeta.

card_number

credit_card_data

string

sí (débito automático activo)

cvv

credit_card_data

int

sí (débito automático activo)

Código de seguridad de la tarjeta.

expiration_date

credit_card_data

string

sí (débito automático activo)

Fecha de expiración de la tarjeta en formato MM/AA.

retries

credit_card_data

int

no

Define la cantidad de veces que se reintenta un pago en caso de ser fallido (ej. fondos insuficentes). Valor por defecto: 1.

Valores permitidos: entre 0 - 4. Si es mayor a 1, se ejecutan los reintentos con un día de diferencia, siempre y cuando el procesador lo permita.

franchise

credit_card_data

string

sí (débito automático activo)

id_type

credit_card_data

string

sí (débito automático activo)

Tipo de documento de identificación de la persona que realiza la transacción.

id

credit_card_data

string

sí (débito automático activo)

Número de documento de identificación de la persona que realiza la transacción.

holder_name

credit_card_data

string

sí (débito automático activo)

Nombre del titular de la tarjeta, sin apellidos.

holder_last_name

credit_card_data

string

sí (débito automático activo)

Apellidos del titular de la tarjeta.

email

credit_card_data

string

sí (débito automático activo)

Dirección de correo electrónico de la persona que realiza la transacción.

phone

credit_card_data

string

sí (débito automático activo)

Número telefónico de la persona que realiza la transacción sin indicativos.

ip

credit_card_data

string

sí (débito automático activo)

Dirección IP del dispositivo origen de la transacción, del usuario final.

header_user_agent

credit_card_data

string

sí (débito automático activo)

header_user_agent de el navegador de el usuario.

line1

credit_card_data

string

sí (débito automático activo)

Línea 1 asociada a la dirección de facturación del usuario.

line2

credit_card_data

string

sí (débito automático activo)

Línea 2 asociada a la dirección de facturación del usuario.

line3

credit_card_data

string

sí (débito automático activo)

Línea 3 asociada a la dirección de facturación del usuario.

country

credit_card_data

string

sí (débito automático activo)

País del usuario.

city

credit_card_data

string

sí (débito automático activo)

Ciudad del usuario.

state

credit_card_data

string

sí (débito automático activo)

Estado o departamento del usuario.

post_code

credit_card_data

string

sí (débito automático activo)

Código postal de usuario.

Para los días que no existan en meses donde se debe realizar un pago, por ejemplo el día 31, el límite para realizar el pago de la suscripción será el último día de dicho mes.

Ejemplos

  • Go

package main

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

type Payload struct {
	Merchant  string `json:"merchant"`
	PlanID    string `json:"plan_id"`
	Checksum  string `json:"checksum"`
	StartDate  string `json:"start_date"`
	Customer  struct {
		FirstName string `json:"first_name"`
		LastName  string `json:"last_name"`
		UserDI    string `json:"user_di"`
		TypeDI    string `json:"type_di"`
		Cellphone string `json:"cellphone"`
		Email     string `json:"email"`
	} `json:"customer"`
}

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

	// Prepare the request payload
	payload := Payload{
		Merchant:  "kuanto",
		PlanID:    "50e25c83-12ba-442f-adf8-6d410b376045",
		Checksum:  "d171f0254271b731d06b91ad97bb0ec284e5997c997597cc8068fc688cb94f6b7dbe6295531e01b52c67cbeb2eddfcfabe29ca12323f118d77239001ed411869",
		StartDate: "12/12/2024"
		Customer: struct {
			FirstName string `json:"first_name"`
			LastName  string `json:"last_name"`
			UserDI    string `json:"user_di"`
			TypeDI    string `json:"type_di"`
			Cellphone string `json:"cellphone"`
			Email     string `json:"email"`
		}{
			FirstName: "user-name",
			LastName:  "last-name",
			UserDI:    "999999999",
			TypeDI:    "CC",
			Cellphone: "+57112321131331",
			Email:     "user@example.com",
		},
	}

	// Create the checksum
	data := payload.Merchant + strconv. + payload.PlanID + "FIXED_HASH"
	checksum := calculateSHA512(data)

	// Update the checksum value in the payload
	payload.Checksum = checksum

	// Convert the payload to JSON
	requestBody, err := json.Marshal(payload)
	if err != nil {
		fmt.Println("Error marshaling request payload:", err)
		return
	}

	// Send the POST request
	resp, err := http.Post(url, "application/json", bytes.NewBuffer(requestBody))
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()

	// Read the response body
	responseBody, 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(responseBody))
}

func calculateSHA512(data string) string {
	hash := sha512.Sum512([]byte(data))
	return hex.EncodeToString(hash[:])
}
  • PHP

<?php

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

// Prepare the request payload
$payload = array(
    "merchant" => "kuanto",
    "plan_id" => "50e25c83-12ba-442f-adf8-6d410b376045",
    "checksum" => "d171f0254271b731d06b91ad97bb0ec284e5997c997597cc8068fc688cb94f6b7dbe6295531e01b52c67cbeb2eddfcfabe29ca12323f118d77239001ed411869",
    "start_date" => "12/12/2024",
    "customer" => array(
        "first_name" => "user-name",
        "last_name" => "last-name",
        "user_di" => "999999999",
        "type_di" => "CC",
        "cellphone" => "+57112321131331",
        "email" => "user@example.com"
    )
);

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

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

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

// Set the request headers
$headers = array(
    'Content-Type: application/json'
);

// Initialize cURL
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// Execute the cURL request
$response = curl_exec($ch);

// Check for cURL errors
if (curl_error($ch)) {
    echo 'Error: ' . curl_error($ch);
    exit;
}

// Close cURL
curl_close($ch);

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

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

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

// Prepare the request payload
const payload = {
  merchant: 'kuanto',
  plan_id: '50e25c83-12ba-442f-adf8-6d410b376045',
  checksum: 'd171f0254271b731d06b91ad97bb0ec284e5997c997597cc8068fc688cb94f6b7dbe6295531e01b52c67cbeb2eddfcfabe29ca12323f118d77239001ed411869',
  start_date: '12/12/2024',
  customer: {
    first_name: 'user-name',
    last_name: 'last-name',
    user_di: '999999999',
    type_di: 'CC',
    cellphone: '+57112321131331',
    email: 'user@example.com',
  },
};

// Create the checksum
const data = payload.merchant + payload.plan_id + 'FIXED_HASH';
const checksum = crypto.createHash('sha512').update(data).digest('hex');

// Update the checksum value in the payload
payload.checksum = checksum;

// Send the POST request
fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(payload),
})
  .then((response) => response.json())
  .then((data) => {
    console.log('Response Body:', data);
  })
  .catch((error) => {
    console.error('Error:', error);
  });
  • 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/v4/subscriptions";

        // Prepare the request payload
        String payload = "{\n" +
                "   \"merchant\":\"kuanto\",\n" +
                "   \"plan_id\":\"50e25c83-12ba-442f-adf8-6d410b376045\",\n" +
                "   \"checksum\":\"d171f0254271b731d06b91ad97bb0ec284e5997c997597cc8068fc688cb94f6b7dbe6295531e01b52c67cbeb2eddfcfabe29ca12323f118d77239001ed411869\",\n" +
                "   \"start_date\":\"12/12/2024\",\n" +
                "   \"customer\":{\n" +
                "      \"first_name\":\"user-name\",\n" +
                "      \"last_name\":\"last-name\",\n" +
                "      \"user_di\":\"999999999\",\n" +
                "      \"type_di\":\"CC\",\n" +
                "      \"cellphone\":\"+57112321131331\",\n" +
                "      \"email\":\"user@example.com\"\n" +
                "   }\n" +
                "}";

        // Create the checksum
        String data = "kuanto" + "50e25c83-12ba-442f-adf8-6d410b376045" + "FIXED_HASH";
        String checksum = getSHA512Checksum(data);

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

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

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

            // Get the response
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                System.out.println("Response Body: " + response.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String getSHA512Checksum(String data) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-512");
            byte[] hashBytes = digest.digest(data.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

import requests
import hashlib
import json
import time

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

# Prepare the request payload
payload = {
    "merchant": "kuanto",
    "plan_id": "50e25c83-12ba-442f-adf8-6d410b376045",
    "checksum": "d171f0254271b731d06b91ad97bb0ec284e5997c997597cc8068fc688cb94f6b7dbe6295531e01b52c67cbeb2eddfcfabe29ca12323f118d77239001ed411869",
    "start_date": "12/12/2024",
    "customer": {
        "first_name": "user-name",
        "last_name": "last-name",
        "user_di": "999999999",
        "type_di": "CC",
        "cellphone": "+57112321131331",
        "email": "user@example.com"
    }
}

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

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

# Send the POST request
response = requests.post(url, json=payload)

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

Last updated