Skip to main content

H2H payments

Process Overview

  1. Create payment, get uuid
  2. Send details to https://api-h2h.alikassa.com/v1/payment
  3. Redirect client to 3DS
  4. After payment, the payer will return to your specified page return_url
  5. Send confirm request, confirm payment

API Endpoint

POSThttps://api-merchant.alikassa.com/v1/payment📋

Headers

HeaderValue
Content-Typeapplication/json
AccountYour account uuid, you can find in Accounts
SignRequest signature
ApplicationIssued Application UUID

Step 1: Create payment, get uuid

Create payment using API:

function requestPayment(string $method, string $account, array $data)
{
$data = json_encode($data);

$privateKey = openssl_pkey_get_private(
file_get_contents(__DIR__ . '/cert/payment/private.pem'),
file_get_contents(__DIR__ . '/cert/payment/password.txt')
);

if ($privateKey === false) {
throw new \Exception('Error cert.');
}

openssl_sign($data, $sign, $privateKey);
$sign = base64_encode($sign);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api-merchant.alikassa.com/' . $method);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Account: ' . $account,
'Sign: ' . $sign,
]);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'AliKassa2.0 API');
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$response = curl_exec($ch);

return json_decode($response, true);
}

requestPayment('v1/payment', '93d5df06-996c-48c3-9847-348d6b580b80', [
'order_id' => (string)time(),
'amount' => 500,
'customer_browser_user_agent' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:84.0) Gecko/20100101 Firefox/84.0',
'customer_ip' => '18.191.80.10',
'success_redirect_id' => 1,
'fail_redirect_id' => 1,
'notification_endpoint_id' => 5,
'service' => 'payment_card_rub_hpp',
'customer_browser_accept_header' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'customer_browser_color_depth' => '32',
'customer_browser_language' => 'ru',
'customer_browser_screen_height' => 1080,
'customer_browser_screen_width' => 1920,
'customer_browser_window_width' => 900,
'customer_browser_window_height' => 640,
'customer_browser_time_different' => -180,
'customer_browser_java_enabled' => 1,
'customer_browser_user_agent' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0',
]);
import { readFileSync } from 'fs';
import { createSign } from 'crypto';
import https from 'https';

async function requestPayment(method, account, data) {
const dataStr = JSON.stringify(data);
const privateKeyPem = readFileSync('cert/payment/private.pem', 'utf8');
const passphrase = readFileSync('cert/payment/password.txt', 'utf8').trim();
const signer = createSign('SHA256');
signer.update(dataStr);
signer.end();
const sign = signer.sign({ key: privateKeyPem, passphrase }, 'base64');

const options = {
hostname: 'api-merchant.alikassa.com',
path: `/${method}`,
method: 'POST',
headers: {
'Content-Type': 'application/json',
Account: account,
Sign: sign,
'User-Agent': 'AliKassa2.0 API',
},
timeout: 30000,
};

return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
let body = '';
res.on('data', (chunk) => (body += chunk));
res.on('end', () => resolve(JSON.parse(body)));
});
req.on('error', reject);
req.write(dataStr);
req.end();
});
}

requestPayment('v1/payment', '93d5df06-996c-48c3-9847-348d6b580b80', {
order_id: String(Date.now()),
amount: 500,
customer_browser_user_agent:
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0',
customer_ip: '18.191.80.10',
success_redirect_id: 1,
fail_redirect_id: 1,
notification_endpoint_id: 5,
service: 'payment_card_rub_hpp',
customer_browser_accept_header:
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
customer_browser_color_depth: '32',
customer_browser_language: 'ru',
customer_browser_screen_height: 1080,
customer_browser_screen_width: 1920,
customer_browser_window_width: 900,
customer_browser_window_height: 640,
customer_browser_time_different: -180,
customer_browser_java_enabled: 1,
});
import json
import base64
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
import requests

def request_payment(method: str, account: str, data: dict):
data_bytes = json.dumps(data).encode('utf-8')
with open('cert/payment/password.txt', 'rb') as f:
password = f.read().strip()
with open('cert/payment/private.pem', 'rb') as f:
private_key = serialization.load_pem_private_key(f.read(), password=password)
signature = private_key.sign(data_bytes, padding.PKCS1v15(), hashes.SHA256())
sign = base64.b64encode(signature).decode('utf-8')
headers = {
'Content-Type': 'application/json',
'Account': account,
'Sign': sign,
'User-Agent': 'AliKassa2.0 API',
}
resp = requests.post(f'https://api-merchant.alikassa.com/{method}', data=data_bytes, headers=headers, timeout=30)
return resp.json()

request_payment('v1/payment', '93d5df06-996c-48c3-9847-348d6b580b80', {
'order_id': str(int(__import__('time').time())),
'amount': 500,
'customer_browser_user_agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0',
'customer_ip': '18.191.80.10',
'success_redirect_id': 1,
'fail_redirect_id': 1,
'notification_endpoint_id': 5,
'service': 'payment_card_rub_hpp',
'customer_browser_accept_header': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'customer_browser_color_depth': '32',
'customer_browser_language': 'ru',
'customer_browser_screen_height': 1080,
'customer_browser_screen_width': 1920,
'customer_browser_window_width': 900,
'customer_browser_window_height': 640,
'customer_browser_time_different': -180,
'customer_browser_java_enabled': 1,
})
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.Signature;
import java.util.Base64;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.bouncycastle.openssl.PEMEncryptedKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import java.io.FileReader;
import java.util.Map;

public class Example {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> data = Map.of(
"order_id", String.valueOf(System.currentTimeMillis()),
"amount", 500,
"customer_browser_user_agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0",
"customer_ip", "18.191.80.10",
"success_redirect_id", 1,
"fail_redirect_id", 1,
"notification_endpoint_id", 5,
"service", "payment_card_rub_hpp",
"customer_browser_accept_header", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"customer_browser_color_depth", "32",
"customer_browser_language", "ru",
"customer_browser_screen_height", 1080,
"customer_browser_screen_width", 1920,
"customer_browser_window_width", 900,
"customer_browser_window_height", 640,
"customer_browser_time_different", -180,
"customer_browser_java_enabled", 1
);
String dataStr = mapper.writeValueAsString(data);
char[] pass = Files.readString(Paths.get("cert/payment/password.txt")).toCharArray();
PEMParser parser = new PEMParser(new FileReader("cert/payment/private.pem"));
PEMEncryptedKeyPair ckp = (PEMEncryptedKeyPair) parser.readObject();
var kp = new JcaPEMKeyConverter().getKeyPair(
ckp.decryptKeyPair(new JcePEMDecryptorProviderBuilder().build(pass))
);
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initSign(kp.getPrivate());
sig.update(dataStr.getBytes(StandardCharsets.UTF_8));
String sign = Base64.getEncoder().encodeToString(sig.sign());
HttpRequest request = HttpRequest.newBuilder()
.uri(java.net.URI.create("https://api-merchant.alikassa.com/v1/payment"))
.header("Content-Type", "application/json")
.header("Account", "93d5df06-996c-48c3-9847-348d6b580b80")
.header("Sign", sign)
.header("User-Agent", "AliKassa2.0 API")
.POST(HttpRequest.BodyPublishers.ofString(dataStr))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(mapper.readValue(response.body(), Object.class));
}
}
package main

import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"io/ioutil"
"net/http"
"time"
)

func signData(data interface{}) string {
dataBytes, _ := json.Marshal(data)
pemBytes, _ := ioutil.ReadFile("cert/payment/private.pem")
passBytes, _ := ioutil.ReadFile("cert/payment/password.txt")
block, _ := pem.Decode(pemBytes)
der, _ := x509.DecryptPEMBlock(block, passBytes)
priv, _ := x509.ParsePKCS1PrivateKey(der)
hash := sha256.Sum256(dataBytes)
sigBytes, _ := rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA256, hash[:])
return base64.StdEncoding.EncodeToString(sigBytes)
}

func requestPayment(method, account string, data interface{}) (map[string]interface{}, error) {
sign := signData(data)
dataBytes, _ := json.Marshal(data)
req, _ := http.NewRequest("POST", "https://api-merchant.alikassa.com/"+method, bytes.NewReader(dataBytes))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Account", account)
req.Header.Set("Sign", sign)
req.Header.Set("User-Agent", "AliKassa2.0 API")
client := &http.Client{Timeout: 30 * time.Second}
resp, _ := client.Do(req)
defer resp.Body.Close()
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
return result, nil
}

func main() {
requestPayment("v1/payment", "93d5df06-996c-48c3-9847-348d6b580b80", map[string]interface{}{
"order_id": time.Now().Unix(),
"amount": 500,
"customer_browser_user_agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0",
"customer_ip": "18.191.80.10",
"success_redirect_id": 1,
"fail_redirect_id": 1,
"notification_endpoint_id": 5,
"service": "payment_card_rub_hpp",
"customer_browser_accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"customer_browser_color_depth": "32",
"customer_browser_language": "ru",
"customer_browser_screen_height": 1080,
"customer_browser_screen_width": 1920,
"customer_browser_window_width": 900,
"customer_browser_window_height": 640,
"customer_browser_time_different": -180,
"customer_browser_java_enabled": 1,
})
}

Step 2: Send details to https://api-h2h.alikassa.com/v1/payment

Request Parameters

* - Required fields

NameTypeDescriptionExample
card_first_name*stringCard first nameIvan
card_last_name*stringCard last nameIvanov
card_number*intCard number4242 4242 4242 4242
card_year*int (2)End date, year, last 2 digits29
card_month*int (2)End date, month08
card_cvc*int (3)CVC cards077
payment_uuid*intAliKassa Uuid
return_url*stringReturn URL (In the link, specify the uuid of the payment)
browser_user_agent*stringBrowser user agentMozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:84.0) Gecko/20100101 Firefox/84.0
browser_accept_header*stringBrowser accept headertext/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
browser_language*stringBrowser languageru
browser_color_depth*int(Color depth) - the number of bits that fit into one pixelscreen.colorDepth
browser_screen_height*intBrowser screen heightscreen.height
browser_screen_width*intBrowser screen widthscreen.width
browser_window_width*intBrowser window widthwindow.innerWidth
browser_window_height*intBrowser window heightwindow.innerHeight
browser_time_different*intTime difference in browser(new Date()).getTimezoneOffset()
browser_java_enabled*intIs java enabled in browser1
browser_ip*ipPayer's IPREMOTE_ADDR

Response

NameDescription
successtrue — successfully completed
false — runtime error
redirectObject of the payer's order for payment

url — ссылка
method — get | post
params — parameters for get or post

Test Cards

  • 4242 4242 4242 4242 — successful payment
  • 5555 5555 5555 4444 — payment error
warning

Validity period - any unexpired, arbitrary CVV code.

Response Examples

Successful Response (HTTP CODE 200)

{
"success": true,
"redirect": {
"url": "https://payment.com/3ds",
"method": "get",
"params": []
}
}

Error Response (HTTP CODE 400)

{
"success": false,
"error": "...",
"errorCode": "..."
}

Step 3: Redirect client to 3DS

After receiving the url, redirect the payer.

Example:

function requestH2H(string $method, string $account, array $data)
{
$privateKey = openssl_pkey_get_private(
file_get_contents(__DIR__ . '/cert/payment/private.pem'),
file_get_contents(__DIR__ . '/cert/payment/password.txt')
);

if ($privateKey === false) {
throw new \Exception('Error cert.');
}

openssl_sign((string)$data['payment_uuid'], $sign, $privateKey);
$sign = base64_encode($sign);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api-h2h.alikassa.com/' . $method);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Account: ' . $account,
'Sign: ' . $sign,
'Application: {APPLICATION_UUID}',
]);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'AliKassa2.0 API');
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

return json_decode(curl_exec($ch), true);
}

$payment = requestH2H('v1/payment', '93d5df06-996c-48c3-9847-348d6b580b80', [
'payment_uuid' => 'a0c0809e-9121-0c08-8fba-ef0227083121',
'return_url' => 'http://site.ru/confirm',
'card_number' => '506900010009002',
'card_year' => '20',
'card_month' => '07',
'card_cvc' => '704',
]);
import { readFileSync } from 'fs';
import { createSign } from 'crypto';
import https from 'https';

async function requestH2H(method, account, data) {
const privateKeyPem = readFileSync('cert/payment/private.pem', 'utf8');
const passphrase = readFileSync('cert/payment/password.txt', 'utf8').trim();
const signer = createSign('SHA256');
signer.update(String(data.payment_uuid));
signer.end();
const sign = signer.sign({ key: privateKeyPem, passphrase }, 'base64');
const body = JSON.stringify(data);
const options = {
hostname: 'api-h2h.alikassa.com',
path: `/${method}`,
method: 'POST',
headers: {
'Content-Type': 'application/json',
Account: account,
Sign: sign,
Application: '{APPLICATION_UUID}',
},
timeout: 30000,
};
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
let response = '';
res.on('data', (chunk) => (response += chunk));
res.on('end', () => resolve(JSON.parse(response)));
});
req.on('error', reject);
req.write(body);
req.end();
});
}

(async () => {
const payment = await requestH2H(
'v1/payment',
'93d5df06-996c-48c3-9847-348d6b580b80',
{
payment_uuid: 'a0c0809e-9121-0c08-8fba-ef0227083121',
return_url: 'http://site.ru/confirm',
card_number: '506900010009002',
card_year: '20',
card_month: '07',
card_cvc: '704',
}
);
console.log(payment);
})();
import json, base64
import requests
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding

def request_h2h(method: str, account: str, data: dict):
private_key = serialization.load_pem_private_key(
open('cert/payment/private.pem','rb').read(),
password=open('cert/payment/password.txt','rb').read().strip()
)
signature = private_key.sign(
str(data['payment_uuid']).encode(),
padding.PKCS1v15(),
hashes.SHA256()
)
sign = base64.b64encode(signature).decode()
headers = {
'Content-Type': 'application/json',
'Account': account,
'Sign': sign,
'Application': '{APPLICATION_UUID}',
}
resp = requests.post(
f'https://api-h2h.alikassa.com/{method}',
json=data, headers=headers, timeout=30
)
return resp.json()

payment = request_h2h('v1/payment', '93d5df06-996c-48c3-9847-348d6b580b80', {
'payment_uuid': 'a0c0809e-9121-0c08-8fba-ef0227083121',
'return_url': 'http://site.ru/confirm',
'card_number': '506900010009002',
'card_year': '20',
'card_month': '07',
'card_cvc': '704',
})
print(payment)
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.Signature;
import java.util.Base64;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.bouncycastle.openssl.PEMEncryptedKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import java.io.FileReader;
import java.util.Map;

public class Example {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> data = Map.of(
"payment_uuid", "a0c0809e-9121-0c08-8fba-ef0227083121",
"return_url", "http://site.ru/confirm",
"card_number", "506900010009002",
"card_year", "20",
"card_month", "07",
"card_cvc", "704"
);
char[] pass = Files.readString(Paths.get("cert/payment/password.txt")).toCharArray();
PEMParser parser = new PEMParser(new FileReader("cert/payment/private.pem"));
var ckp = (PEMEncryptedKeyPair) parser.readObject();
var kp = new JcaPEMKeyConverter().getKeyPair(
ckp.decryptKeyPair(new JcePEMDecryptorProviderBuilder().build(pass))
);
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initSign(kp.getPrivate());
sig.update(data.get("payment_uuid").toString().getBytes(StandardCharsets.UTF_8));
String sign = Base64.getEncoder().encodeToString(sig.sign());
HttpRequest req = HttpRequest.newBuilder()
.uri(java.net.URI.create("https://api-h2h.alikassa.com/v1/payment"))
.header("Content-Type","application/json")
.header("Account", "93d5df06-996c-48c3-9847-348d6b580b80")
.header("Sign", sign)
.header("Application", "{APPLICATION_UUID}")
.POST(HttpRequest.BodyPublishers.ofString(mapper.writeValueAsString(data)))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> res = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(mapper.readValue(res.body(), Map.class));
}
}
package main

import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"io/ioutil"
"net/http"
"time"
)

func signUUID(uuid string) string {
pemBytes, _ := ioutil.ReadFile("cert/payment/private.pem")
passBytes, _ := ioutil.ReadFile("cert/payment/password.txt")
block, _ := pem.Decode(pemBytes)
der, _ := x509.DecryptPEMBlock(block, passBytes)
priv, _ := x509.ParsePKCS1PrivateKey(der)
hash := sha256.Sum256([]byte(uuid))
sigBytes, _ := rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA256, hash[:])
return base64.StdEncoding.EncodeToString(sigBytes)
}

func requestH2H(method, account string, data map[string]interface{}) (map[string]interface{}, error) {
sign := signUUID(data["payment_uuid"].(string))
body, _ := json.Marshal(data)
req, _ := http.NewRequest("POST", "https://api-h2h.alikassa.com/"+method, bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Account", account)
req.Header.Set("Sign", sign)
req.Header.Set("Application", "{APPLICATION_UUID}")
client := &http.Client{Timeout: 30 * time.Second}
resp, _ := client.Do(req)
defer resp.Body.Close()
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
return result, nil
}

func main() {
payment, _ := requestH2H("v1/payment", "93d5df06-996c-48c3-9847-348d6b580b80", map[string]interface{}{
"payment_uuid": "a0c0809e-9121-0c08-8fba-ef0227083121",
"return_url": "http://site.ru/confirm",
"card_number": "506900010009002",
"card_year": "20",
"card_month": "07",
"card_cvc": "704",
})
fmt.Println(payment)
}
warning

You only need to sign payment_uuid.

Step 4: After payment, the payer will return to your specified page return_url

After payment, the payer will return to your specified page return_url.

Step 5: Send confirm request, confirm payment

After payment, the payer will return to the return_url page, before checking the status of the payment, send us a confirmation.

Send all the POST data you received and also the uuid of the payment.

Parameters

* - Required fields

NameTypeDescription
payment_uuid*stringAliKassa Uuid
dataarrayPOST data

Response

NameDescription
successtrue — successfully completed
false — runtime error

Example:

requestH2H('v1/payment/confirm', '93d5df06-996c-48c3-9847-348d6b580b80', [
'payment_uuid' => $_GET['uuid'],
'data' => $_POST,
]);
(async () => {
const response = await requestH2H(
'v1/payment/confirm',
'93d5df06-996c-48c3-9847-348d6b580b80',
{
payment_uuid: req.query.uuid,
data: req.body,
}
);
console.log(response);
})();
response = request_h2h(
'v1/payment/confirm',
'93d5df06-996c-48c3-9847-348d6b580b80',
{
'payment_uuid': request.args.get('uuid'),
'data': request.form.to_dict(),
}
)
print(response)
var response = Example.requestH2H(
"v1/payment/confirm",
"93d5df06-996c-48c3-9847-348d6b580b80",
Map.of(
"payment_uuid", req.getParameter("uuid"),
"data", Map.ofEntries(req.getParameterMap().entrySet().stream()
.map(e -> Map.entry(e.getKey(), e.getValue()[0]))
.toArray(Map.Entry[]::new))
)
);
System.out.println(response);
response, err := requestH2H(
"v1/payment/confirm",
"93d5df06-996c-48c3-9847-348d6b580b80",
map[string]interface{}{
"payment_uuid": r.URL.Query().Get("uuid"),
"data": r.PostForm,
},
)
fmt.Println(response, err)