1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-14 15:13:29 +01:00
invoiceninja/app/PaymentDrivers/MolliePaymentDriver.php

424 lines
14 KiB
PHP
Raw Normal View History

2021-07-23 13:47:01 +02:00
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
2023-01-28 23:21:40 +01:00
* @copyright Copyright (c) 2023. Invoice Ninja LLC (https://invoiceninja.com)
2021-07-23 13:47:01 +02:00
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\PaymentDrivers;
2021-08-04 14:59:15 +02:00
use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest;
2021-07-29 15:13:38 +02:00
use App\Http\Requests\Gateways\Mollie\Mollie3dsRequest;
2021-07-23 13:47:01 +02:00
use App\Http\Requests\Payments\PaymentWebhookRequest;
2021-07-31 13:26:00 +02:00
use App\Jobs\Util\SystemLogger;
2021-11-21 00:13:10 +01:00
use App\Models\Client;
2021-07-23 13:47:01 +02:00
use App\Models\ClientGatewayToken;
use App\Models\GatewayType;
2021-08-04 14:59:15 +02:00
use App\Models\Invoice;
2021-07-23 13:47:01 +02:00
use App\Models\Payment;
use App\Models\PaymentHash;
2021-08-04 14:59:15 +02:00
use App\Models\PaymentType;
2021-07-23 13:47:01 +02:00
use App\Models\SystemLog;
use App\PaymentDrivers\Mollie\Bancontact;
use App\PaymentDrivers\Mollie\BankTransfer;
2021-07-23 14:43:32 +02:00
use App\PaymentDrivers\Mollie\CreditCard;
2021-10-04 15:43:11 +02:00
use App\PaymentDrivers\Mollie\IDEAL;
2021-09-24 23:04:47 +02:00
use App\PaymentDrivers\Mollie\KBC;
2021-07-23 13:47:01 +02:00
use App\Utils\Traits\MakesHash;
2021-08-02 14:53:44 +02:00
use Illuminate\Support\Facades\Validator;
use Mollie\Api\Exceptions\ApiException;
2021-07-23 14:43:32 +02:00
use Mollie\Api\MollieApiClient;
2021-07-23 13:47:01 +02:00
class MolliePaymentDriver extends BaseDriver
{
use MakesHash;
/**
* @var bool
2021-07-23 13:47:01 +02:00
*/
public $refundable = true;
/**
* @var true
*/
public $token_billing = true;
/**
* @var true
*/
public $can_authorise_credit_card = true;
/**
2021-07-23 14:43:32 +02:00
* @var MollieApiClient
2021-07-23 13:47:01 +02:00
*/
public $gateway;
/**
* @var mixed
*/
public $payment_method;
/**
* @var string[]
*/
public static $methods = [
GatewayType::CREDIT_CARD => CreditCard::class,
GatewayType::BANCONTACT => Bancontact::class,
GatewayType::BANK_TRANSFER => BankTransfer::class,
2021-09-24 23:04:47 +02:00
GatewayType::KBC => KBC::class,
2021-10-04 15:43:11 +02:00
GatewayType::IDEAL => IDEAL::class,
2021-07-23 13:47:01 +02:00
];
2021-07-23 14:43:32 +02:00
const SYSTEM_LOG_TYPE = SystemLog::TYPE_MOLLIE;
2021-07-23 13:47:01 +02:00
2021-07-23 14:43:32 +02:00
public function init(): self
2021-07-23 13:47:01 +02:00
{
2021-07-23 14:43:32 +02:00
$this->gateway = new MollieApiClient();
$this->gateway->setApiKey(
$this->company_gateway->getConfigField('apiKey'),
);
2021-07-23 13:47:01 +02:00
return $this;
}
public function gatewayTypes(): array
{
$types = [];
$types[] = GatewayType::CREDIT_CARD;
$types[] = GatewayType::BANCONTACT;
$types[] = GatewayType::BANK_TRANSFER;
2021-09-24 23:04:47 +02:00
$types[] = GatewayType::KBC;
2021-10-04 15:43:11 +02:00
$types[] = GatewayType::IDEAL;
2021-07-23 13:47:01 +02:00
return $types;
}
public function setPaymentMethod($payment_method_id)
{
$class = self::$methods[$payment_method_id];
2021-07-23 14:43:32 +02:00
2021-07-23 13:47:01 +02:00
$this->payment_method = new $class($this);
2021-07-23 14:43:32 +02:00
2021-07-23 13:47:01 +02:00
return $this;
}
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)
{
2021-08-02 16:33:37 +02:00
$this->init();
try {
$payment = $this->gateway->payments->get($payment->transaction_reference);
$refund = $this->gateway->payments->refund($payment, [
'amount' => [
'currency' => $this->client->currency()->code,
'value' => $this->convertToMollieAmount((float) $amount),
],
]);
if ($refund->status === 'refunded') {
SystemLogger::dispatch(
['server_response' => $refund, 'data' => request()->all()],
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_SUCCESS,
SystemLog::TYPE_MOLLIE,
$this->client,
$this->client->company
);
return [
'transaction_reference' => $refund->id,
'transaction_response' => json_encode($refund),
'success' => $refund->status === 'refunded' ? true : false,
'description' => $refund->description,
'code' => 200,
];
}
2021-08-04 14:31:47 +02:00
return [
'transaction_reference' => $refund->id,
'transaction_response' => json_encode($refund),
'success' => true,
'description' => $refund->description,
'code' => 0,
];
2021-08-02 16:33:37 +02:00
} catch (ApiException $e) {
SystemLogger::dispatch(
['server_response' => $refund, 'data' => request()->all()],
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_FAILURE,
SystemLog::TYPE_MOLLIE,
$this->client,
2021-11-21 21:04:58 +01:00
$this->client->company
2021-08-02 16:33:37 +02:00
);
nlog($e->getMessage());
return [
'transaction_reference' => null,
'transaction_response' => $e->getMessage(),
'success' => false,
'description' => $e->getMessage(),
'code' => $e->getCode(),
];
}
2021-07-23 13:47:01 +02:00
}
public function tokenBilling(ClientGatewayToken $cgt, PaymentHash $payment_hash)
{
2021-08-04 14:59:15 +02:00
$amount = array_sum(array_column($payment_hash->invoices(), 'amount')) + $payment_hash->fee_total;
$invoice = Invoice::whereIn('id', $this->transformKeys(array_column($payment_hash->invoices(), 'invoice_id')))->withTrashed()->first();
if ($invoice) {
$description = "Invoice {$invoice->number} for {$amount} for client {$this->client->present()->name()}";
} else {
$description = "Payment with no invoice for amount {$amount} for client {$this->client->present()->name()}";
}
$request = new PaymentResponseRequest();
$request->setMethod('POST');
$request->request->add(['payment_hash' => $payment_hash->hash]);
$this->init();
try {
$payment = $this->gateway->payments->create([
'amount' => [
'currency' => $this->client->currency()->code,
'value' => $this->convertToMollieAmount($amount),
],
'mandateId' => $cgt->token,
'customerId' => $cgt->gateway_customer_reference,
'sequenceType' => 'recurring',
'description' => $description,
2023-02-21 08:04:59 +01:00
'idempotencyKey' => uniqid("st", true),
2021-08-04 14:59:15 +02:00
'webhookUrl' => $this->company_gateway->webhookUrl(),
]);
if ($payment->status === 'paid') {
$this->confirmGatewayFee($request);
$data = [
'payment_method' => $cgt->token,
'payment_type' => PaymentType::CREDIT_CARD_OTHER,
'amount' => $amount,
'transaction_reference' => $payment->id,
'gateway_type_id' => GatewayType::CREDIT_CARD,
];
$payment = $this->createPayment($data, Payment::STATUS_COMPLETED);
SystemLogger::dispatch(
['response' => $payment, 'data' => $data],
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_SUCCESS,
SystemLog::TYPE_MOLLIE,
2021-11-21 21:04:58 +01:00
$this->client,
$this->client->company
2021-08-04 14:59:15 +02:00
);
return $payment;
}
$this->unWindGatewayFees($payment_hash);
2021-10-17 12:40:40 +02:00
$this->sendFailureMail($payment->details);
2021-08-04 14:59:15 +02:00
$message = [
'server_response' => $payment,
'data' => $payment_hash->data,
];
SystemLogger::dispatch(
$message,
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_FAILURE,
SystemLog::TYPE_CHECKOUT,
2021-11-21 21:04:58 +01:00
$this->client,
$this->client->company
2021-08-04 14:59:15 +02:00
);
return false;
} catch (ApiException $e) {
$this->unWindGatewayFees($payment_hash);
$data = [
'status' => '',
'error_type' => '',
'error_code' => $e->getCode(),
'param' => '',
'message' => $e->getMessage(),
];
SystemLogger::dispatch($data, SystemLog::CATEGORY_GATEWAY_RESPONSE, SystemLog::EVENT_GATEWAY_FAILURE, SystemLog::TYPE_MOLLIE, $this->client, $this->client->company);
}
2021-07-23 13:47:01 +02:00
}
2021-08-02 14:53:44 +02:00
public function processWebhookRequest(PaymentWebhookRequest $request)
2021-07-23 13:47:01 +02:00
{
// Allow app to catch up with webhook request.
sleep(2);
2021-08-02 14:53:44 +02:00
$validator = Validator::make($request->all(), [
'id' => ['required', 'starts_with:tr'],
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
2021-08-02 16:33:37 +02:00
2021-08-02 14:53:44 +02:00
$this->init();
2021-08-02 14:53:44 +02:00
$codes = [
'open' => Payment::STATUS_PENDING,
'canceled' => Payment::STATUS_CANCELLED,
'pending' => Payment::STATUS_PENDING,
'expired' => Payment::STATUS_CANCELLED,
'failed' => Payment::STATUS_FAILED,
'paid' => Payment::STATUS_COMPLETED,
];
nlog($request->id);
2021-08-02 14:53:44 +02:00
try {
$payment = $this->gateway->payments->get($request->id);
2021-11-21 00:13:10 +01:00
$record = Payment::withTrashed()->where('transaction_reference', $request->id)->first();
2021-08-02 14:53:44 +02:00
if ($record) {
2021-11-21 00:13:10 +01:00
$client = $record->client;
$this->client = $client;
} else {
2021-11-21 21:20:53 +01:00
$client = Client::withTrashed()->find($this->decodePrimaryKey($payment->metadata->client_id));
$this->client = $client;
// sometimes if the user is not returned to the site with a response from Mollie
2021-11-25 12:27:02 +01:00
// we may not have a payment record - in these cases we need to re-construct the payment
// record from the meta data in the payment hash.
if ($payment && property_exists($payment->metadata, 'hash') && $payment->metadata->hash) {
/* Harvest Payment Hash*/
$payment_hash = PaymentHash::where('hash', $payment->metadata->hash)->first();
/* If we are here, then we do not have access to the class payment hash, so lets set it here*/
$this->payment_hash = $payment_hash;
$data = [
'gateway_type_id' => $payment->metadata->gateway_type_id,
'amount' => $amount = array_sum(array_column($payment_hash->invoices(), 'amount')) + $payment_hash->fee_total,
'payment_type' => $payment->metadata->payment_type_id,
'transaction_reference' => $payment->id,
];
$record = $this->createPayment(
$data,
$codes[$payment->status]
);
}
2021-11-21 00:13:10 +01:00
}
$message = [
'server_response' => $payment,
'data' => $request->all(),
];
$response = SystemLog::EVENT_GATEWAY_FAILURE;
if ($record) {
if (in_array($payment->status, ['canceled', 'expired', 'failed'])) {
$record->service()->deletePayment(false); //sometimes mollie does not return but we still decrement the paid to date, this is incorrect.
}
2022-05-24 12:12:24 +02:00
2021-11-21 00:13:10 +01:00
$record->status_id = $codes[$payment->status];
$record->save();
$response = SystemLog::EVENT_GATEWAY_SUCCESS;
}
SystemLogger::dispatch(
$message,
SystemLog::CATEGORY_GATEWAY_RESPONSE,
$response,
SystemLog::TYPE_MOLLIE,
2021-11-21 21:04:58 +01:00
$client,
$client->company
2021-11-21 00:13:10 +01:00
);
2021-08-02 14:53:44 +02:00
return response()->json([], 200);
2021-08-02 16:33:37 +02:00
} catch (ApiException $e) {
2021-08-02 14:53:44 +02:00
return response()->json(['message' => $e->getMessage(), 'gatewayStatusCode' => $e->getCode()], 500);
}
2021-07-23 13:47:01 +02:00
}
2021-07-31 13:26:00 +02:00
2021-07-29 15:13:38 +02:00
public function process3dsConfirmation(Mollie3dsRequest $request)
{
$this->init();
$this->setPaymentHash($request->getPaymentHash());
try {
$payment = $this->gateway->payments->get($request->getPaymentId());
return (new CreditCard($this))->processSuccessfulPayment($payment);
2021-07-31 13:26:00 +02:00
} catch (\Mollie\Api\Exceptions\ApiException $e) {
2021-07-29 15:13:38 +02:00
return (new CreditCard($this))->processUnsuccessfulPayment($e);
}
}
2021-07-31 13:26:00 +02:00
public function detach(ClientGatewayToken $token)
{
$this->init();
try {
$this->gateway->mandates->revokeForId($token->gateway_customer_reference, $token->token);
} catch (\Mollie\Api\Exceptions\ApiException $e) {
SystemLogger::dispatch(
[
'server_response' => $e->getMessage(),
'data' => request()->all(),
],
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_FAILURE,
SystemLog::TYPE_MOLLIE,
$this->client,
$this->client->company
);
}
}
2021-08-02 15:49:50 +02:00
/**
* Convert the amount to the format that Mollie supports.
*
* @param mixed|float $amount
* @return string
2021-08-02 15:49:50 +02:00
*/
public function convertToMollieAmount($amount): string
{
return \number_format((float) $amount, 2, '.', '');
}
2021-07-23 13:47:01 +02:00
}