1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace PhpLightning\Invoice\Domain\BackendInvoice; |
6
|
|
|
|
7
|
|
|
use PhpLightning\Http\HttpFacadeInterface; |
8
|
|
|
|
9
|
|
|
final class LnbitsBackendInvoice implements BackendInvoiceInterface |
10
|
|
|
{ |
11
|
|
|
private HttpFacadeInterface $httpFacade; |
12
|
|
|
|
13
|
|
|
/** @var array{api_key:string, api_endpoint:string} */ |
14
|
|
|
private array $options; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @param array{api_key:string, api_endpoint:string} $options |
18
|
|
|
*/ |
19
|
1 |
|
public function __construct( |
20
|
|
|
HttpFacadeInterface $httpFacade, |
21
|
|
|
array $options, |
22
|
|
|
) { |
23
|
1 |
|
$this->httpFacade = $httpFacade; |
24
|
1 |
|
$this->options = $options; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @return array { |
29
|
|
|
* status: string, |
30
|
|
|
* reason: string, |
31
|
|
|
* } |
32
|
|
|
*/ |
33
|
1 |
|
public function requestInvoice(float $satsAmount, string $metadata): array |
34
|
|
|
{ |
35
|
1 |
|
$endpoint = $this->options['api_endpoint'] . '/api/v1/payments'; |
36
|
|
|
|
37
|
1 |
|
$content = [ |
38
|
1 |
|
'out' => false, |
39
|
1 |
|
'amount' => $satsAmount, |
40
|
1 |
|
'unhashed_description' => bin2hex($metadata), |
41
|
1 |
|
// 'description_hash' => hash('sha256', $metadata), |
42
|
1 |
|
]; |
43
|
|
|
|
44
|
1 |
|
$response = $this->httpFacade->post($endpoint, [ |
45
|
1 |
|
'headers' => [ |
46
|
1 |
|
'Content-Type' => 'application/json', |
47
|
1 |
|
'X-Api-Key' => $this->options['api_key'], |
48
|
1 |
|
], |
49
|
1 |
|
'body' => json_encode($content, JSON_THROW_ON_ERROR), |
50
|
1 |
|
]); |
51
|
|
|
|
52
|
1 |
|
if ($response !== null) { |
53
|
|
|
/** @var array{payment_request?: string} $responseJson */ |
54
|
1 |
|
$responseJson = json_decode($response, true, 512, JSON_THROW_ON_ERROR); |
55
|
|
|
|
56
|
1 |
|
return [ |
57
|
1 |
|
'status' => 'OK', |
58
|
1 |
|
'pr' => $responseJson['payment_request'] ?? 'No payment_request found', |
59
|
1 |
|
]; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return [ |
63
|
|
|
'status' => 'ERROR', |
64
|
|
|
'reason' => 'Backend "LnBits" unreachable', |
65
|
|
|
]; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|