/
Stripe.php
293 lines (243 loc) · 11.1 KB
/
Stripe.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
<?php
/**
* Copyright 2022-2024 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
use Stripe\StripeClient;
class Payment_Adapter_Stripe implements FOSSBilling\InjectionAwareInterface
{
protected ?Pimple\Container $di = null;
private StripeClient $stripe;
public function setDi(Pimple\Container $di): void
{
$this->di = $di;
}
public function getDi(): ?Pimple\Container
{
return $this->di;
}
public function __construct(private $config)
{
if ($this->config['test_mode']) {
if (!isset($this->config['test_api_key'])) {
throw new Payment_Exception('The ":pay_gateway" payment gateway is not fully configured. Please configure the :missing', [':pay_gateway' => 'Stripe', ':missing' => 'Test API Key'], 4001);
}
if (!isset($this->config['test_pub_key'])) {
throw new Payment_Exception('The ":pay_gateway" payment gateway is not fully configured. Please configure the :missing', [':pay_gateway' => 'Stripe', ':missing' => 'Test publishable key'], 4001);
}
$this->stripe = new StripeClient($this->config['test_api_key']);
} else {
if (!isset($this->config['api_key'])) {
throw new Payment_Exception('The ":pay_gateway" payment gateway is not fully configured. Please configure the :missing', [':pay_gateway' => 'Stripe', ':missing' => 'API key'], 4001);
}
if (!isset($this->config['pub_key'])) {
throw new Payment_Exception('The ":pay_gateway" payment gateway is not fully configured. Please configure the :missing', [':pay_gateway' => 'Stripe', ':missing' => 'Publishable key'], 4001);
}
$this->stripe = new StripeClient($this->config['api_key']);
}
}
public static function getConfig()
{
return [
'supports_one_time_payments' => true,
'description' => 'You authenticate to the Stripe API by providing one of your API keys in the request. You can manage your API keys from your account.',
'logo' => [
'logo' => 'stripe.png',
'height' => '30px',
'width' => '65px',
],
'form' => [
'pub_key' => [
'text', [
'label' => 'Live publishable key:',
],
],
'api_key' => [
'text', [
'label' => 'Live Secret key:',
],
],
'test_pub_key' => [
'text', [
'label' => 'Test Publishable key:',
'required' => false,
],
],
'test_api_key' => [
'text', [
'label' => 'Test Secret key:',
'required' => false,
],
],
],
];
}
public function getHtml($api_admin, $invoice_id, $subscription)
{
$invoiceModel = $this->di['db']->load('Invoice', $invoice_id);
return $this->_generateForm($invoiceModel);
}
public function getAmountInCents(Model_Invoice $invoice)
{
$invoiceService = $this->di['mod_service']('Invoice');
return $invoiceService->getTotalWithTax($invoice) * 100;
}
public function getInvoiceTitle(Model_Invoice $invoice)
{
$invoiceItems = $this->di['db']->getAll('SELECT title from invoice_item WHERE invoice_id = :invoice_id', [':invoice_id' => $invoice->id]);
$params = [
':id' => sprintf('%05s', $invoice->nr),
':serie' => $invoice->serie,
':title' => $invoiceItems[0]['title'],
];
$title = __trans('Payment for invoice :serie:id [:title]', $params);
if ((is_countable($invoiceItems) ? count($invoiceItems) : 0) > 1) {
$title = __trans('Payment for invoice :serie:id', $params);
}
return $title;
}
public function logError($e, Model_Transaction $tx)
{
$body = $e->getJsonBody();
$err = $body['error'];
$tx->txn_status = $err['type'];
$tx->error = $err['message'];
$tx->status = 'processed';
$tx->updated_at = date('Y-m-d H:i:s');
$this->di['db']->store($tx);
if (DEBUG) {
error_log(json_encode($e->getJsonBody()));
}
throw new Exception($tx->error);
}
public function processTransaction($api_admin, $id, $data, $gateway_id)
{
$tx = $this->di['db']->getExistingModelById('Transaction', $id);
// Use the invoice ID associated with the transaction or else fallback to the ID passed via GET.
if ($tx->invoice_id) {
$invoice = $this->di['db']->getExistingModelById('Invoice', $tx->invoice_id);
} else {
$invoice = $this->di['db']->getExistingModelById('Invoice', $data['invoice_id']);
$tx->invoice_id = $invoice->id;
}
try {
$charge = $this->stripe->paymentIntents->retrieve(
$data['get']['payment_intent'],
[]
);
$tx->txn_status = $charge->status;
$tx->txn_id = $charge->id;
$tx->amount = $charge->amount / 100;
$tx->currency = $charge->currency;
$bd = [
'amount' => $tx->amount,
'description' => 'Stripe transaction ' . $charge->id,
'type' => 'transaction',
'rel_id' => $tx->id,
];
// Only pay the invoice if the transaction has 'succeeded' on Stripe's end & the associated FOSSBilling transaction hasn't been processed.
if ($charge->status == 'succeeded' && $tx->status !== 'processed') {
// Instance the services we need
$clientService = $this->di['mod_service']('client');
$invoiceService = $this->di['mod_service']('Invoice');
// Update the account funds
$client = $this->di['db']->getExistingModelById('Client', $invoice->client_id);
$clientService->addFunds($client, $bd['amount'], $bd['description'], $bd);
// Now pay the invoice / batch pay if there's no invoice associated with the transaction
if ($tx->invoice_id) {
$invoiceService->payInvoiceWithCredits($invoice);
} else {
$invoiceService->doBatchPayWithCredits(['client_id' => $client->id]);
}
}
} catch (Stripe\Exception\CardException|Stripe\Exception\InvalidRequestException|Stripe\Exception\AuthenticationException|Stripe\Exception\ApiConnectionException|Stripe\Exception\ApiErrorException $e) {
$this->logError($e, $tx);
throw new FOSSBilling\Exception('There was an error when processing the transaction');
}
$paymentStatus = match ($charge->status) {
'succeeded' => 'processed',
'pending' => 'received',
'failed' => 'error',
};
$tx->status = $paymentStatus;
$tx->updated_at = date('Y-m-d H:i:s');
$this->di['db']->store($tx);
}
protected function _generateForm(Model_Invoice $invoice): string
{
$intent = $this->stripe->paymentIntents->create([
'amount' => $this->getAmountInCents($invoice),
'currency' => $invoice->currency,
'description' => $this->getInvoiceTitle($invoice),
'automatic_payment_methods' => ['enabled' => true],
'receipt_email' => $invoice->buyer_email,
]);
$pubKey = ($this->config['test_mode']) ? $this->config['test_pub_key'] : $this->config['pub_key'];
$dataAmount = $this->getAmountInCents($invoice);
$settingService = $this->di['mod_service']('System');
$title = $this->getInvoiceTitle($invoice);
$form = '<form id="payment-form" data-secret=":intent_secret">
<div class="loading" style="display:none;"><span>{% trans \'Loading ...\' %}</span></div>
<script src="https://js.stripe.com/v3/"></script>
<div id="error-message">
<!-- Error messages will be displayed here -->
</div>
<div id="payment-element">
<!-- Stripe Elements will create form elements here -->
</div>
<button id="submit" class="btn btn-primary mt-2" style="margin-top: 0.5em;">Submit</button>
<script>
const stripe = Stripe(\':pub_key\');
var elements = stripe.elements({
clientSecret: \':intent_secret\',
});
var paymentElement = elements.create(\'payment\', {
billingDetails: {
name: \'never\',
email: \'never\',
},
});
paymentElement.mount(\'#payment-element\');
const form = document.getElementById(\'payment-form\');
form.addEventListener(\'submit\', async (event) => {
event.preventDefault();
const {error} = await stripe.confirmPayment({
elements,
confirmParams: {
return_url: \':callbackUrl&redirect=true&invoice_hash=:invoice_hash\',
payment_method_data: {
billing_details: {
name: \':buyer_name\',
email: \':buyer_email\',
},
},
},
});
if (error) {
const messageContainer = document.querySelector(\'#error-message\');
messageContainer.innerHTML = `<p class="alert alert-danger">${error.message}</p>`;
}
});
</script>
</form>';
$payGatewayService = $this->di['mod_service']('Invoice', 'PayGateway');
$payGateway = $this->di['db']->findOne('PayGateway', 'gateway = "Stripe"');
$bindings = [
':pub_key' => $pubKey,
':intent_secret' => $intent->client_secret,
':amount' => $dataAmount,
':currency' => $invoice->currency,
':description' => $title,
':buyer_email' => $invoice->buyer_email,
':buyer_name' => trim($invoice->buyer_first_name . ' ' . $invoice->buyer_last_name),
':callbackUrl' => $payGatewayService->getCallbackUrl($payGateway, $invoice),
':redirectUrl' => $this->di['tools']->url('invoice/' . $invoice->hash),
':invoice_hash' => $invoice->hash,
];
return strtr($form, $bindings);
}
}