1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-09-20 16:31:33 +02:00
invoiceninja/app/PaymentDrivers/GoCardlessPaymentDriver.php

346 lines
11 KiB
PHP
Raw Normal View History

2021-09-28 18:24:52 +02:00
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
2022-04-27 05:20:41 +02:00
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
2021-09-28 18:24:52 +02:00
*
* @license https://www.elastic.co/licensing/elastic-license
2021-09-28 18:24:52 +02:00
*/
namespace App\PaymentDrivers;
use App\Events\Payment\PaymentFailed;
2021-09-30 15:55:34 +02:00
use App\Http\Requests\Payments\PaymentWebhookRequest;
2021-09-30 10:03:44 +02:00
use App\Jobs\Util\SystemLogger;
2021-09-28 18:24:52 +02:00
use App\Models\ClientGatewayToken;
use App\Models\GatewayType;
use App\Models\Payment;
use App\Models\PaymentHash;
2021-09-30 10:03:44 +02:00
use App\Models\PaymentType;
2021-09-28 18:24:52 +02:00
use App\Models\SystemLog;
use App\Utils\Traits\MakesHash;
class GoCardlessPaymentDriver extends BaseDriver
{
use MakesHash;
public $refundable = true;
public $token_billing = true;
public $can_authorise_credit_card = true;
2021-09-29 16:54:14 +02:00
public \GoCardlessPro\Client $gateway;
2021-09-28 18:24:52 +02:00
public $payment_method;
public static $methods = [
GatewayType::BANK_TRANSFER => \App\PaymentDrivers\GoCardless\ACH::class,
GatewayType::DIRECT_DEBIT => \App\PaymentDrivers\GoCardless\DirectDebit::class,
2021-10-19 18:01:42 +02:00
GatewayType::SEPA => \App\PaymentDrivers\GoCardless\SEPA::class,
GatewayType::INSTANT_BANK_PAY => \App\PaymentDrivers\GoCardless\InstantBankPay::class,
2021-09-28 18:24:52 +02:00
];
const SYSTEM_LOG_TYPE = SystemLog::TYPE_GOCARDLESS;
public function setPaymentMethod($payment_method_id)
{
$class = self::$methods[$payment_method_id];
$this->payment_method = new $class($this);
return $this;
}
public function gatewayTypes(): array
{
$types = [];
if (
$this->client
&& isset($this->client->country)
&& in_array($this->client->country->iso_3166_3, ['USA'])
) {
$types[] = GatewayType::BANK_TRANSFER;
}
if (
$this->client
&& isset($this->client->country)
&& in_array($this->client->country->iso_3166_3, ['GBR'])
) {
$types[] = GatewayType::DIRECT_DEBIT;
}
2021-10-19 18:01:42 +02:00
if ($this->client->currency()->code === 'EUR') {
$types[] = GatewayType::SEPA;
}
2021-11-11 17:51:04 +01:00
if ($this->client->currency()->code === 'GBP') {
$types[] = GatewayType::INSTANT_BANK_PAY;
}
return $types;
}
2021-09-29 14:44:23 +02:00
public function init(): self
{
$this->gateway = new \GoCardlessPro\Client([
'access_token' => $this->company_gateway->getConfigField('accessToken'),
'environment' => $this->company_gateway->getConfigField('testMode') ? \GoCardlessPro\Environment::SANDBOX : \GoCardlessPro\Environment::LIVE,
]);
return $this;
}
2021-09-28 18:24:52 +02:00
public function authorizeView(array $data)
{
return $this->payment_method->authorizeView($data);
}
public function authorizeResponse($request)
{
return $this->payment_method->authorizeResponse($request);
}
public function processPaymentView(array $data)
{
return $this->payment_method->paymentView($data);
}
public function processPaymentResponse($request)
{
return $this->payment_method->paymentResponse($request);
}
public function refund(Payment $payment, $amount, $return_client_response = false)
{
// ..
}
public function tokenBilling(ClientGatewayToken $cgt, PaymentHash $payment_hash)
{
2021-09-30 10:03:44 +02:00
$amount = array_sum(array_column($payment_hash->invoices(), 'amount')) + $payment_hash->fee_total;
$converted_amount = $this->convertToGoCardlessAmount($amount, $this->client->currency()->precision);
$this->init();
try {
$payment = $this->gateway->payments()->create([
'params' => [
'amount' => $converted_amount,
'currency' => $this->client->getCurrencyCode(),
'metadata' => [
'payment_hash' => $this->payment_hash->hash,
],
'links' => [
'mandate' => $cgt->token,
],
],
]);
if ($payment->status === 'pending_submission') {
$this->confirmGatewayFee();
$data = [
'payment_method' => $cgt->hashed_id,
'payment_type' => PaymentType::ACH,
'amount' => $amount,
'transaction_reference' => $payment->id,
'gateway_type_id' => GatewayType::BANK_TRANSFER,
];
2022-03-19 11:21:36 +01:00
$payment = $this->createPayment($data, Payment::STATUS_PENDING);
2021-09-30 10:03:44 +02:00
SystemLogger::dispatch(
['response' => $payment, 'data' => $data],
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_SUCCESS,
SystemLog::TYPE_GOCARDLESS,
$this->client,
$this->client->company
);
return $payment;
}
2021-10-17 12:40:40 +02:00
$this->sendFailureMail($payment->status);
2021-09-30 10:03:44 +02:00
$message = [
'server_response' => $payment,
'data' => $payment_hash->data,
];
SystemLogger::dispatch(
$message,
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_FAILURE,
SystemLog::TYPE_GOCARDLESS,
$this->client,
$this->client->company
);
return false;
} catch (\Exception $exception) {
$this->unWindGatewayFees($this->payment_hash);
$data = [
'status' => '',
'error_type' => '',
'error_code' => $exception->getCode(),
'param' => '',
'message' => $exception->getMessage(),
];
SystemLogger::dispatch($data, SystemLog::CATEGORY_GATEWAY_RESPONSE, SystemLog::EVENT_GATEWAY_FAILURE, SystemLog::TYPE_GOCARDLESS, $this->client, $this->client->company);
}
2021-09-28 18:24:52 +02:00
}
2021-09-30 08:42:30 +02:00
public function convertToGoCardlessAmount($amount, $precision)
{
return \round(($amount * pow(10, $precision)), 0);
}
2021-09-30 14:55:46 +02:00
public function detach(ClientGatewayToken $token)
{
$this->init();
try {
$this->gateway->mandates()->cancel($token->token);
} catch (\Exception $e) {
nlog($e->getMessage());
SystemLogger::dispatch(
[
'server_response' => $e->getMessage(),
'data' => request()->all(),
],
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_FAILURE,
SystemLog::TYPE_GOCARDLESS,
$this->client,
$this->client->company
);
}
}
2021-09-30 15:55:34 +02:00
public function processWebhookRequest(PaymentWebhookRequest $request)
{
// Allow app to catch up with webhook request.
$this->init();
nlog('GoCardless Event');
2022-04-22 03:59:37 +02:00
nlog($request->all());
if (! $request->has('events')) {
nlog('No GoCardless events to process in response?');
return response()->json([], 200);
}
2022-05-13 23:30:40 +02:00
sleep(1);
2021-09-30 15:55:34 +02:00
foreach ($request->events as $event) {
2022-06-13 12:34:40 +02:00
if ($event['action'] === 'confirmed' || $event['action'] === 'paid_out') {
nlog('Searching for transaction reference');
2022-05-13 23:30:40 +02:00
2021-09-30 15:55:34 +02:00
$payment = Payment::query()
->where('transaction_reference', $event['links']['payment'])
2022-06-10 23:02:24 +02:00
->where('company_id', $request->getCompany()->id)
2021-09-30 15:55:34 +02:00
->first();
if ($payment) {
$payment->status_id = Payment::STATUS_COMPLETED;
$payment->save();
nlog('GoCardless completed');
} else {
nlog('I was unable to find the payment for this reference');
2021-09-30 15:55:34 +02:00
}
2022-03-19 11:33:53 +01:00
//finalize payments on invoices here.
2021-09-30 15:55:34 +02:00
}
if ($event['action'] === 'failed' && array_key_exists('payment', $event['links'])) {
2021-09-30 15:55:34 +02:00
$payment = Payment::query()
->where('transaction_reference', $event['links']['payment'])
2022-06-10 23:02:24 +02:00
->where('company_id', $request->getCompany()->id)
2021-09-30 15:55:34 +02:00
->first();
if ($payment) {
$payment->status_id = Payment::STATUS_FAILED;
$payment->save();
nlog('GoCardless completed');
2021-09-30 15:55:34 +02:00
}
}
//billing_request fulfilled
//PaymentHash::whereJsonContains('data->billing_request', 'BRQ0001BQ8JESEV')->first();
//i need to build more context here, i need the client , the payment hash resolved and update the class properties.
//after i resolve the payment hash, ensure the invoice has not been marked as paid and the payment does not already exist.
//if it does exist, ensure it is completed and not pending.
// if($event['action'] == 'fulfilled' && array_key_exists('billing_request', $event['links'])) {
// $billing_request = $this->go_cardless->gateway->billingRequests()->get(
// $event['links']['billing_request']
// );
// $payment = $this->go_cardless->gateway->payments()->get(
// $billing_request->payment_request->links->payment
// );
// if ($billing_request->status === 'fulfilled') {
// $this->processSuccessfulPayment($payment);
// }
// }
2021-09-30 15:55:34 +02:00
}
return response()->json([], 200);
}
public function processSuccessfulPayment(\GoCardlessPro\Resources\Payment $payment, array $data = [])
{
$data = [
'payment_method' => $payment->links->mandate,
'payment_type' => PaymentType::INSTANT_BANK_PAY,
'amount' => $this->go_cardless->payment_hash->data->amount_with_fee,
'transaction_reference' => $payment->id,
'gateway_type_id' => GatewayType::INSTANT_BANK_PAY,
];
$payment = $this->go_cardless->createPayment($data, Payment::STATUS_COMPLETED);
SystemLogger::dispatch(
['response' => $payment, 'data' => $data],
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_SUCCESS,
SystemLog::TYPE_GOCARDLESS,
$this->go_cardless->client,
$this->go_cardless->client->company,
);
}
2021-11-25 11:45:52 +01:00
public function ensureMandateIsReady($token)
{
try {
2021-11-25 11:45:52 +01:00
$this->init();
$mandate = $this->gateway->mandates()->get($token);
if ($mandate->status !== 'active') {
throw new \Exception(ctrans('texts.gocardless_mandate_not_ready'));
}
} catch (\Exception $exception) {
throw new \App\Exceptions\PaymentFailed($exception->getMessage());
}
}
2021-09-28 18:24:52 +02:00
}