1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-18 09:04:35 +01:00
invoiceninja/app/PaymentDrivers/BaseDriver.php

527 lines
17 KiB
PHP
Raw Normal View History

2020-06-09 13:17:26 +02:00
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
2020-06-09 13:17:26 +02:00
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2021. Invoice Ninja LLC (https://invoiceninja.com)
2020-06-09 13:17:26 +02:00
*
* @license https://opensource.org/licenses/AAL
*/
namespace App\PaymentDrivers;
2020-08-12 04:02:21 +02:00
use App\Events\Invoice\InvoiceWasPaid;
use App\Events\Payment\PaymentWasCreated;
use App\Exceptions\PaymentFailed;
2020-08-17 00:58:52 +02:00
use App\Factory\PaymentFactory;
2020-08-30 00:00:57 +02:00
use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest;
2021-02-16 11:14:53 +01:00
use App\Jobs\Mail\NinjaMailer;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Jobs\Mail\PaymentFailureMailer;
use App\Jobs\Util\SystemLogger;
2021-02-16 11:14:53 +01:00
use App\Mail\Admin\ClientPaymentFailureObject;
2020-06-09 13:17:26 +02:00
use App\Models\Client;
2020-09-09 12:05:10 +02:00
use App\Models\ClientContact;
2020-07-08 04:20:44 +02:00
use App\Models\ClientGatewayToken;
2020-06-09 13:17:26 +02:00
use App\Models\CompanyGateway;
use App\Models\Invoice;
use App\Models\Payment;
2020-09-01 01:28:37 +02:00
use App\Models\PaymentHash;
use App\Models\SystemLog;
use App\Services\Subscription\SubscriptionService;
2020-08-12 04:02:21 +02:00
use App\Utils\Ninja;
2020-06-09 13:17:26 +02:00
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\SystemLogTrait;
2020-10-28 11:10:49 +01:00
use Checkout\Library\Exceptions\CheckoutHttpException;
use Exception;
2020-11-26 00:42:59 +01:00
use Illuminate\Http\Request;
2020-11-27 12:08:42 +01:00
use Illuminate\Support\Carbon;
2020-12-03 01:05:22 +01:00
use Illuminate\Support\Str;
2020-06-09 13:17:26 +02:00
/**
* Class BaseDriver.
2020-06-09 13:17:26 +02:00
*/
2020-06-09 14:54:22 +02:00
class BaseDriver extends AbstractPaymentDriver
2020-06-09 13:17:26 +02:00
{
use SystemLogTrait;
use MakesHash;
/* The company gateway instance*/
public $company_gateway;
/* The Invitation */
2020-06-15 13:42:46 +02:00
public $invitation;
2020-06-09 13:17:26 +02:00
/* Gateway capabilities */
2020-06-15 13:42:46 +02:00
public $refundable = false;
2020-06-09 13:17:26 +02:00
/* Token billing */
2020-06-15 13:42:46 +02:00
public $token_billing = false;
2020-06-09 13:17:26 +02:00
/* Authorise payment methods */
2020-06-15 13:42:46 +02:00
public $can_authorise_credit_card = false;
2020-06-09 13:17:26 +02:00
2020-06-12 02:19:26 +02:00
/* The client */
2020-06-15 13:42:46 +02:00
public $client;
2020-11-25 22:07:09 +01:00
/* The initialized gateway driver class*/
2020-06-15 13:42:46 +02:00
public $payment_method;
2020-06-09 13:17:26 +02:00
2020-11-25 22:07:09 +01:00
/* PaymentHash */
public $payment_hash;
2020-11-25 22:07:09 +01:00
/* Array of payment methods */
2020-06-16 05:49:45 +02:00
public static $methods = [];
/** @var array */
public $required_fields = [];
2020-06-16 02:21:40 +02:00
2020-06-10 14:42:10 +02:00
public function __construct(CompanyGateway $company_gateway, Client $client = null, $invitation = false)
2020-06-09 13:17:26 +02:00
{
$this->company_gateway = $company_gateway;
$this->invitation = $invitation;
$this->client = $client;
}
/**
* Required fields for client to fill, to proceed with gateway actions.
*
* @return array[]
*/
public function getClientRequiredFields(): array
{
return [];
}
2020-06-12 02:19:26 +02:00
/**
* Authorize a payment method.
*
* Returns a reusable token for storage for future payments
2020-11-27 12:08:42 +01:00
*
2020-11-25 22:07:09 +01:00
* @param array $data
* @return mixed Return a view for collecting payment method information
2020-06-12 02:19:26 +02:00
*/
2020-11-27 12:08:42 +01:00
public function authorizeView(array $data)
{
}
2020-06-12 02:19:26 +02:00
/**
2020-11-25 22:07:09 +01:00
* The payment authorization response
2020-11-27 12:08:42 +01:00
*
* @param Request $request
2020-11-25 22:07:09 +01:00
* @return mixed Return a response for collecting payment method information
2020-06-12 02:19:26 +02:00
*/
2020-11-27 12:08:42 +01:00
public function authorizeResponse(Request $request)
{
}
2020-11-25 22:07:09 +01:00
/**
* Process a payment
2020-11-27 12:08:42 +01:00
*
* @param array $data
2020-11-25 22:07:09 +01:00
* @return mixed Return a view for the payment
*/
2020-11-27 12:08:42 +01:00
public function processPaymentView(array $data)
{
}
2020-11-25 22:07:09 +01:00
/**
* Process payment response
2020-11-27 12:08:42 +01:00
*
2020-11-25 22:07:09 +01:00
* @param Request $request
* @return mixed Return a response for the payment
*/
2020-11-27 12:08:42 +01:00
public function processPaymentResponse(Request $request)
{
}
2020-06-12 02:19:26 +02:00
/**
* Executes a refund attempt for a given amount with a transaction_reference.
*
2020-06-24 03:15:51 +02:00
* @param Payment $payment The Payment Object
2020-06-12 02:19:26 +02:00
* @param float $amount The amount to be refunded
2020-10-12 06:10:34 +02:00
* @param bool $return_client_response Whether the method needs to return a response (otherwise we assume an unattended payment)
* @return mixed
2020-06-12 02:19:26 +02:00
*/
2020-11-27 12:08:42 +01:00
public function refund(Payment $payment, $amount, $return_client_response = false)
{
}
2020-11-25 22:07:09 +01:00
/**
* Process an unattended payment.
*
* @param ClientGatewayToken $cgt The client gateway token object
* @param PaymentHash $payment_hash The Payment hash containing the payment meta data
* @return void The payment response
*/
2020-11-27 12:08:42 +01:00
public function tokenBilling(ClientGatewayToken $cgt, PaymentHash $payment_hash)
{
}
2020-06-09 13:17:26 +02:00
2020-06-15 13:42:46 +02:00
/**
* Set the inbound request payment method type for access.
*
2020-06-15 13:42:46 +02:00
* @param int $payment_method_id The Payment Method ID
*/
2020-11-27 12:08:42 +01:00
public function setPaymentMethod($payment_method_id)
{
}
2020-11-25 22:07:09 +01:00
/************************** Helper methods *************************************/
2020-06-16 02:21:40 +02:00
public function setPaymentHash(PaymentHash $payment_hash)
{
$this->payment_hash = $payment_hash;
return $this;
}
/**
* Helper method to attach invoices to a payment.
*
2020-10-28 11:10:49 +01:00
* @param Payment $payment The payment
* @param PaymentHash $payment_hash
* @return Payment The payment object
*/
2020-09-01 01:28:37 +02:00
public function attachInvoices(Payment $payment, PaymentHash $payment_hash): Payment
{
2020-09-01 01:28:37 +02:00
$paid_invoices = $payment_hash->invoices();
$invoices = Invoice::whereIn('id', $this->transformKeys(array_column($paid_invoices, 'invoice_id')))->get();
$payment->invoices()->sync($invoices);
$invoices->each(function ($invoice) use ($payment) {
2021-01-24 21:55:04 +01:00
event(new InvoiceWasPaid($invoice, $payment, $payment->company, Ninja::eventVars()));
2020-08-12 04:02:21 +02:00
});
2020-09-01 01:28:37 +02:00
return $payment->service()->applyNumber()->save();
}
2020-07-08 04:20:44 +02:00
2020-08-17 00:58:52 +02:00
/**
* Create a payment from an online payment.
*
2020-08-17 00:58:52 +02:00
* @param array $data Payment data
* @param int $status The payment status_id
* @return Payment The payment object
*/
public function createPayment($data, $status = Payment::STATUS_COMPLETED): Payment
{
$this->confirmGatewayFee();
2021-03-17 16:12:25 +01:00
2020-08-17 00:58:52 +02:00
$payment = PaymentFactory::create($this->client->company->id, $this->client->user->id);
$payment->client_id = $this->client->id;
$payment->company_gateway_id = $this->company_gateway->id;
$payment->status_id = $status;
$payment->currency_id = $this->client->getSetting('currency_id');
$payment->date = Carbon::now();
$payment->gateway_type_id = $data['gateway_type_id'];
2021-01-27 11:38:28 +01:00
$client_contact = $this->getContact();
$client_contact_id = $client_contact ? $client_contact->id : null;
$payment->amount = $data['amount'];
$payment->type_id = $data['payment_type'];
$payment->transaction_reference = $data['transaction_reference'];
$payment->client_contact_id = $client_contact_id;
$payment->save();
$this->payment_hash->payment_id = $payment->id;
$this->payment_hash->save();
$this->attachInvoices($payment, $this->payment_hash);
2021-01-06 06:54:04 +01:00
if($this->payment_hash->credits_total() > 0)
$payment = $payment->service()->applyCredits($this->payment_hash)->save();
$payment->service()->updateInvoicePayment($this->payment_hash);
2021-01-27 15:58:19 +01:00
if ($this->client->getSetting('client_online_payment_notification'))
$payment->service()->sendEmail();
event(new PaymentWasCreated($payment, $payment->company, Ninja::eventVars()));
if (property_exists($this->payment_hash->data, 'billing_context')) {
$billing_subscription = \App\Models\Subscription::find($this->payment_hash->data->billing_context->billing_subscription_id);
(new SubscriptionService($billing_subscription))->completePurchase($this->payment_hash);
}
2021-03-17 16:12:25 +01:00
2020-08-17 00:58:52 +02:00
return $payment->service()->applyNumber()->save();
}
2020-08-30 00:00:57 +02:00
/**
* When a successful payment is made, we need to append the gateway fee
* to an invoice.
*
2020-08-30 00:00:57 +02:00
* @param PaymentResponseRequest $request The incoming payment request
* @return void Success/Failure
*/
public function confirmGatewayFee() :void
2020-08-30 00:00:57 +02:00
{
2020-08-30 14:00:19 +02:00
2020-08-30 00:00:57 +02:00
/*Payment invoices*/
$payment_invoices = $this->payment_hash->invoices();
2020-11-25 22:07:09 +01:00
/*Fee charged at gateway*/
$fee_total = $this->payment_hash->fee_total;
2020-08-30 00:00:57 +02:00
/*Hydrate invoices*/
2020-08-30 14:00:19 +02:00
$invoices = Invoice::whereIn('id', $this->transformKeys(array_column($payment_invoices, 'invoice_id')))->get();
2020-08-30 00:00:57 +02:00
$invoices->each(function ($invoice) use ($fee_total) {
if (collect($invoice->line_items)->contains('type_id', '3')) {
$invoice->service()->toggleFeesPaid()->save();
$invoice->client->service()->updateBalance($fee_total)->save();
2021-01-21 05:42:30 +01:00
$invoice->ledger()->updateInvoiceBalance($fee_total, "Gateway fee adjustment for invoice {$invoice->number}");
}
});
2020-08-30 00:00:57 +02:00
}
2020-09-09 12:05:10 +02:00
/**
2020-10-28 11:10:49 +01:00
* In case of a payment failure we should always
* return the invoice to its original state
2020-10-28 11:10:49 +01:00
*
* @param PaymentHash $payment_hash The payment hash containing the list of invoices
2020-10-28 11:10:49 +01:00
* @return void
*/
public function unWindGatewayFees(PaymentHash $payment_hash)
{
$invoices = Invoice::whereIn('id', $this->transformKeys(array_column($payment_hash->invoices(), 'invoice_id')))->get();
$invoices->each(function ($invoice) {
$invoice->service()->removeUnpaidGatewayFees();
});
}
2020-09-09 12:05:10 +02:00
/**
* Return the contact if possible.
*
* @return ClientContact The ClientContact object
*/
public function getContact()
{
if ($this->invitation) {
return ClientContact::find($this->invitation->client_contact_id);
} elseif (auth()->guard('contact')->user()) {
return auth()->user();
} else {
return false;
}
}
2020-10-26 14:40:50 +01:00
/**
* Store payment method as company gateway token.
2020-10-28 11:10:49 +01:00
*
* @param array $data
* @return null|ClientGatewayToken
2020-10-26 14:40:50 +01:00
*/
public function storeGatewayToken(array $data, array $additional = []): ?ClientGatewayToken
2020-10-26 14:40:50 +01:00
{
$company_gateway_token = new ClientGatewayToken();
$company_gateway_token->company_id = $this->client->company->id;
$company_gateway_token->client_id = $this->client->id;
$company_gateway_token->token = $data['token'];
$company_gateway_token->company_gateway_id = $this->company_gateway->id;
$company_gateway_token->gateway_type_id = $data['payment_method_id'];
$company_gateway_token->meta = $data['payment_meta'];
foreach ($additional as $key => $value) {
$company_gateway_token->{$key} = $value;
}
2020-10-26 14:40:50 +01:00
$company_gateway_token->save();
if ($this->client->gateway_tokens->count() == 1) {
$this->client->gateway_tokens()->update(['is_default' => 0]);
$company_gateway_token->is_default = 1;
$company_gateway_token->save();
}
return $company_gateway_token;
}
public function processInternallyFailedPayment($gateway, $e)
{
2021-02-01 22:33:04 +01:00
$this->unWindGatewayFees($this->payment_hash);
2020-10-28 11:10:49 +01:00
if ($e instanceof CheckoutHttpException) {
$error = $e->getBody();
}
2021-02-01 06:30:28 +01:00
else if ($e instanceof Exception) {
$error = $e->getMessage();
2021-03-17 16:12:25 +01:00
}
else
2021-02-01 06:30:28 +01:00
$error = $e->getMessage();
2021-02-01 22:33:04 +01:00
PaymentFailureMailer::dispatch(
$gateway->client,
$error,
$gateway->client->company,
2021-02-01 12:26:42 +01:00
$this->payment_hash
);
2021-02-16 11:14:53 +01:00
$nmo = new NinjaMailerObject;
$nmo->mailable = new NinjaMailer( (new ClientPaymentFailureObject($gateway->client, $error, $gateway->client->company, $this->payment_hash))->build() );
$nmo->company = $gateway->client->company;
$nmo->settings = $gateway->client->company->settings;
$invoices = Invoice::whereIn('id', $this->transformKeys(array_column($this->payment_hash->invoices(), 'invoice_id')))->get();
$invoices->first()->invitations->each(function ($invitation) {
if ($invitation->contact->send_email && $invitation->contact->email) {
$nmo->to_user = $invitation->contact;
NinjaMailerJob::dispatch($nmo);
}
});
2021-02-02 06:11:33 +01:00
SystemLogger::dispatch(
2020-10-27 13:44:16 +01:00
$gateway->payment_hash,
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_ERROR,
$gateway::SYSTEM_LOG_TYPE,
2020-10-27 13:44:16 +01:00
$gateway->client,
);
throw new PaymentFailed($error, $e->getCode());
}
/**
* Wrapper method for checking if resource is good.
2020-11-27 12:08:42 +01:00
*
* @param mixed $resource
* @return bool
*/
public function checkRequiredResource($resource): bool
{
if (is_null($resource) || empty($resource)) {
return true;
}
return false;
}
public function checkRequirements()
{
if ($this->company_gateway->require_billing_address) {
if ($this->checkRequiredResource(auth()->user('contact')->client->address1)) {
$this->required_fields[] = 'billing_address1';
}
if ($this->checkRequiredResource(auth()->user('contact')->client->address2)) {
$this->required_fields[] = 'billing_address2';
}
if ($this->checkRequiredResource(auth()->user('contact')->client->city)) {
$this->required_fields[] = 'billing_city';
}
if ($this->checkRequiredResource(auth()->user('contact')->client->state)) {
$this->required_fields[] = 'billing_state';
}
if ($this->checkRequiredResource(auth()->user('contact')->client->postal_code)) {
$this->required_fields[] = 'billing_postal_code';
}
if ($this->checkRequiredResource(auth()->user('contact')->client->country_id)) {
$this->required_fields[] = 'billing_country';
}
}
if ($this->company_gateway->require_shipping_address) {
if ($this->checkRequiredResource(auth()->user('contact')->client->shipping_address1)) {
$this->required_fields[] = 'shipping_address1';
}
if ($this->checkRequiredResource(auth()->user('contact')->client->shipping_address2)) {
$this->required_fields[] = 'shipping_address2';
}
if ($this->checkRequiredResource(auth()->user('contact')->client->shipping_city)) {
$this->required_fields[] = 'shipping_city';
}
if ($this->checkRequiredResource(auth()->user('contact')->client->shipping_state)) {
$this->required_fields[] = 'shipping_state';
}
if ($this->checkRequiredResource(auth()->user('contact')->client->shipping_postal_code)) {
$this->required_fields[] = 'shipping_postal_code';
}
if ($this->checkRequiredResource(auth()->user('contact')->client->shipping_country_id)) {
$this->required_fields[] = 'shipping_country';
}
}
if ($this->company_gateway->require_client_name) {
if ($this->checkRequiredResource(auth()->user('contact')->client->name)) {
$this->required_fields[] = 'name';
}
}
if ($this->company_gateway->require_client_phone) {
if ($this->checkRequiredResource(auth()->user('contact')->client->phone)) {
$this->required_fields[] = 'phone';
}
}
if ($this->company_gateway->require_contact_email) {
if ($this->checkRequiredResource(auth()->user('contact')->email)) {
$this->required_fields[] = 'contact_email';
}
}
if ($this->company_gateway->require_contact_name) {
if ($this->checkRequiredResource(auth()->user('contact')->first_name)) {
$this->required_fields[] = 'contact_first_name';
}
if ($this->checkRequiredResource(auth()->user('contact')->last_name)) {
$this->required_fields[] = 'contact_last_name';
}
}
if ($this->company_gateway->require_postal_code) {
// In case "require_postal_code" is true, we don't need billing address.
foreach ($this->required_fields as $position => $field) {
if (Str::startsWith($field, 'billing')) {
unset($this->required_fields[$position]);
}
2020-11-27 12:08:42 +01:00
}
if ($this->checkRequiredResource(auth()->user('contact')->client->postal_code)) {
$this->required_fields[] = 'postal_code';
}
}
return $this;
}
2020-12-09 15:17:48 +01:00
public function getCompanyGatewayId(): int
{
return $this->company_gateway->id;
}
2021-01-11 23:06:56 +01:00
public function logSuccessfulGatewayResponse($response, $gateway_const)
{
SystemLogger::dispatch(
$response,
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_SUCCESS,
$gateway_const,
$this->client,
);
}
2020-06-09 13:17:26 +02:00
}