Платежи H2H
Обзор процесса
- Создать платеж, получить uuid
- Отправить данные на
https://api-h2h.alikassa.io/v1/payment
- Переадресовать клиента на 3DS по redirect
- После оплаты плательщик вернется на указанную вашу страницу
return_url
- Отправить запрос confirm (подтверждение платежа)
API Эндпоинт
POSThttps://api-merchant.alikassa.io/v1/payment📋
Заголовки
Заголовок | Значение |
---|---|
Content-Type | application/json |
Account | Ваш uuid счета (вы можете найти в разделе Счета) |
Sign | Подпись запроса |
Application | Выданный Application UUID |
Шаг 1: Создать платеж, получить uuid
Создайте платеж, используя 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.io/' . $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',
]);
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('SHA1');
signer.update(dataStr);
signer.end();
const sign = signer.sign({ key: privateKeyPem, passphrase }, 'base64');
const options = {
hostname: 'api-merchant.alikassa.io',
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',
});
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.SHA1())
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.io/{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',
})
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",
);
byte[] dataBytes = mapper.writeValueAsBytes(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 privateKey = new JcaPEMKeyConverter()
.getKeyPair(ckp.decryptKeyPair(new JcePEMDecryptorProviderBuilder().build(pass)))
.getPrivate();
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initSign(privateKey);
sig.update(dataBytes);
String sign = Base64.getEncoder().encodeToString(sig.sign());
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(java.net.URI.create("https://api-merchant.alikassa.io/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.ofByteArray(dataBytes))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}
package main
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"net/http"
"time"
)
func main() {
data := map[string]interface{}{
"order_id": fmt.Sprintf("%d", 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",
}
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 := sha1.Sum(dataBytes)
sigBytes, _ := rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA1, hash[:])
sign := base64.StdEncoding.EncodeToString(sigBytes)
req, _ := http.NewRequest("POST", "https://api-merchant.alikassa.io/v1/payment", bytes.NewBuffer(dataBytes))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Account", "93d5df06-996c-48c3-9847-348d6b580b80")
req.Header.Set("Sign", sign)
req.Header.Set("User-Agent", "AliKassa2.0 API")
client := &http.Client{}
resp, _ := client.Do(req)
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
Шаг 2: Отправить данные на https://api-h2h.alikassa.io/v1/payment
Параметры запроса
* - Обязательные поля
Название | Тип | Описание | Пример |
---|---|---|---|
card_first_name* | string | Имя держателя карты | Ivan |
card_last_name* | string | Фамилия держателя карты | Ivanov |
card_number* | int | Номер карты | 4242 4242 4242 4242 |
card_year* | int (2) | Срок окончания (последние 2 цифры года) | 29 |
card_month* | int (2) | Срок окончания (месяц) | 08 |
card_cvc* | int (3) | CVC карты | 077 |
payment_uuid* | int | AliKassa Uuid | |
return_url* | string | URL для возврата (в ссылке укажите uuid платежа) | |
browser_user_agent* | string | User agent пользователя | Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:84.0) Gecko/20100101 Firefox/84.0 |
browser_accept_header* | string | Заголовок браузера Accept | text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8 |
browser_language* | string | Язык браузера | ru |
browser_color_depth* | int | (Глубина цвета) – количество бит, которые вмещаются в один пиксель | screen.colorDepth |
browser_screen_height* | int | Высота экрана браузера | screen.height |
browser_screen_width* | int | Ширина экрана браузера | screen.width |
browser_window_width* | int | Ширина окна браузера | window.innerWidth |
browser_window_height* | int | Высота окна браузера | window.innerHeight |
browser_time_different* | int | Разница во времени в браузере | (new Date()).getTimezoneOffset() |
browser_java_enabled* | int | Включен ли java в браузере | 1 |
browser_ip* | ip | IP плательщика | REMOTE_ADDR |
Ответ
Название | Описание |
---|---|
success | true — успешно выполнено false — ошибка выполнения |
redirect | Object редиректа плательщика для оплаты url — ссылка method — get | post params — параметры для get или post |
Тестовые карты
4242 4242 4242 4242
— успешный платеж5555 5555 5555 4444
— ошибка платежа
Предупреждение
Срок действия — любой непросроченный, код CVV произвольный.
Примеры ответов
Успешный ответ (HTTP CODE 200)
{
"success": true,
"redirect": {
"url": "https://payment.com/3ds",
"method": "get",
"params": []
}
}
Ошибка ответа (HTTP CODE 400)
{
"success": false,
"error": "...",
"errorCode": "..."
}
Шаг 3: Переадресовать клиента на 3DS по redirect
После получения url переадресуйте плательщика.
Пример:
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.io/' . $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('SHA1');
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.io',
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.SHA1()
)
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.io/{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("SHA1withRSA");
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.io/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/sha1"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"io/ioutil"
"net/http"
"time"
"fmt"
)
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 := sha1.Sum([]byte(uuid))
sigBytes, _ := rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA1, 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.io/"+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)
}
Предупреждение
Подписывать нужно только payment_uuid
.
Шаг 4: После оплаты плательщик вернется на указанную вашу страницу return_url
После оплаты плательщик вернется на указанную вашу страницу return_url
.
Шаг 5: Отправить запрос confirm (подтверждение платежа)
После оплаты плательщик вернется на страницу return_url
, прежде чем проверить статус платежа, отправьте нам подтверждение.
Отправьте все данные POST которые вы получили и также uuid платежа.
Параметры
* - Обязательные поля
Название | Тип | Описание |
---|---|---|
payment_uuid* | string | AliKassa Uuid |
data | array | Данные POST |
Ответ
Название | Описание |
---|---|
success | true — успешно выполнено false — ошибка выполнения |
Пример:
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)