Files
kashilo/docs/pow-server/btcpay-invoice.php

68 lines
1.7 KiB
PHP

<?php
require __DIR__ . '/config.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit;
}
$input = json_decode(file_get_contents('php://input'), true);
$listingId = $input['listingId'] ?? null;
if (!$listingId) {
http_response_code(400);
echo json_encode(['error' => 'Missing listingId']);
exit;
}
$payload = json_encode([
'amount' => LISTING_FEE,
'currency' => LISTING_FEE_CURRENCY,
'metadata' => [
'listingId' => $listingId,
'orderId' => 'listing-' . $listingId,
],
]);
$url = BTCPAY_BASE_URL . '/api/v1/stores/' . BTCPAY_STORE_ID . '/invoices';
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\nAuthorization: token " . BTCPAY_API_KEY . "\r\n",
'content' => $payload,
'ignore_errors' => true,
],
]);
$response = file_get_contents($url, false, $context);
if ($response === false) {
http_response_code(502);
echo json_encode(['error' => 'Failed to connect to payment server']);
exit;
}
// Extract HTTP status from response headers
$statusCode = 500;
if (isset($http_response_header[0]) && preg_match('/\d{3}/', $http_response_header[0], $matches)) {
$statusCode = (int)$matches[0];
}
$data = json_decode($response, true);
if ($statusCode >= 400) {
http_response_code($statusCode);
echo json_encode(['error' => $data['message'] ?? 'Invoice creation failed']);
exit;
}
echo json_encode([
'invoiceId' => $data['id'] ?? null,
'checkoutLink' => $data['checkoutLink'] ?? null,
'status' => $data['status'] ?? null,
'expirationTime' => $data['expirationTime'] ?? null,
]);