1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-09-21 08:51:34 +02:00
invoiceninja/app/PaymentDrivers/Stripe/ACH.php

343 lines
13 KiB
PHP
Raw Normal View History

2020-06-09 14:40:55 +02:00
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
2020-06-09 14:40:55 +02:00
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2021. Invoice Ninja LLC (https://invoiceninja.com)
2020-06-09 14:40:55 +02:00
*
2021-06-16 08:58:16 +02:00
* @license https://www.elastic.co/licensing/elastic-license
2020-06-09 14:40:55 +02:00
*/
namespace App\PaymentDrivers\Stripe;
use App\Exceptions\PaymentFailed;
2021-06-23 00:15:03 +02:00
use App\Http\Requests\ClientPortal\PaymentMethod\VerifyPaymentMethodRequest;
use App\Http\Requests\Request;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
2020-06-09 14:40:55 +02:00
use App\Jobs\Util\SystemLogger;
use App\Mail\Gateways\ACHVerificationNotification;
2020-06-09 14:40:55 +02:00
use App\Models\ClientGatewayToken;
use App\Models\GatewayType;
use App\Models\Invoice;
2020-06-09 14:40:55 +02:00
use App\Models\Payment;
use App\Models\PaymentHash;
2020-06-09 14:40:55 +02:00
use App\Models\PaymentType;
use App\Models\SystemLog;
use App\PaymentDrivers\StripePaymentDriver;
use App\Utils\Traits\MakesHash;
use Exception;
use Stripe\Customer;
2020-11-02 16:29:02 +01:00
use Stripe\Exception\CardException;
2020-06-09 14:40:55 +02:00
use Stripe\Exception\InvalidRequestException;
class ACH
{
use MakesHash;
2020-06-09 14:40:55 +02:00
/** @var StripePaymentDriver */
public $stripe;
public function __construct(StripePaymentDriver $stripe)
{
$this->stripe = $stripe;
}
public function authorizeView(array $data)
{
$data['gateway'] = $this->stripe;
2020-06-09 14:40:55 +02:00
return render('gateways.stripe.ach.authorize', array_merge($data));
}
public function authorizeResponse(Request $request)
2020-06-09 14:40:55 +02:00
{
$this->stripe->init();
$stripe_response = json_decode($request->input('gateway_response'));
$customer = $this->stripe->findOrCreateCustomer();
2020-06-09 14:40:55 +02:00
try {
2021-07-20 06:49:04 +02:00
$source = Customer::createSource($customer->id, ['source' => $stripe_response->token->id], $this->stripe->stripe_connect_auth);
2020-06-09 14:40:55 +02:00
} catch (InvalidRequestException $e) {
throw new PaymentFailed($e->getMessage(), $e->getCode());
2020-06-09 14:40:55 +02:00
}
$client_gateway_token = $this->storePaymentMethod($source, $request->input('method'), $customer);
2020-06-09 14:40:55 +02:00
2021-08-10 10:13:04 +02:00
$verification = route('client.payment_methods.verification', ['payment_method' => $client_gateway_token->hashed_id, 'method' => GatewayType::BANK_TRANSFER], false);
$mailer = new NinjaMailerObject();
2021-08-10 10:13:04 +02:00
$mailer->mailable = new ACHVerificationNotification(
auth()->guard('contact')->user()->client->company,
route('client.contact_login', ['contact_key' => auth()->guard('contact')->user()->contact_key, 'next' => $verification])
2021-08-10 10:13:04 +02:00
);
$mailer->company = auth()->guard('contact')->user()->client->company;
$mailer->settings = auth()->guard('contact')->user()->client->company->settings;
$mailer->to_user = auth()->guard('contact')->user();
NinjaMailerJob::dispatch($mailer);
2020-10-20 17:54:08 +02:00
return redirect()->route('client.payment_methods.verification', ['payment_method' => $client_gateway_token->hashed_id, 'method' => GatewayType::BANK_TRANSFER]);
2020-06-09 14:40:55 +02:00
}
public function verificationView(ClientGatewayToken $token)
{
if (isset($token->meta->state) && $token->meta->state === 'authorized') {
return redirect()
->route('client.payment_methods.show', $token->hashed_id)
->with('message', __('texts.payment_method_verified'));
}
$data = [
'token' => $token,
'gateway' => $this->stripe,
];
return render('gateways.stripe.ach.verify', $data);
2020-06-09 14:40:55 +02:00
}
public function processVerification(Request $request, ClientGatewayToken $token)
2020-06-09 14:40:55 +02:00
{
$request->validate([
'transactions.*' => ['integer', 'min:1'],
]);
if (isset($token->meta->state) && $token->meta->state === 'authorized') {
return redirect()
->route('client.payment_methods.show', $token->hashed_id)
->with('message', __('texts.payment_method_verified'));
}
2020-06-09 14:40:55 +02:00
$this->stripe->init();
2021-08-04 03:31:06 +02:00
$bank_account = Customer::retrieveSource($request->customer, $request->source, [], $this->stripe->stripe_connect_auth);
2020-06-09 14:40:55 +02:00
try {
$bank_account->verify(['amounts' => request()->transactions]);
2020-06-09 14:40:55 +02:00
$meta = $token->meta;
$meta->state = 'authorized';
$token->meta = $meta;
2020-06-09 14:40:55 +02:00
$token->save();
return redirect()
->route('client.payment_methods.show', $token->hashed_id)
->with('message', __('texts.payment_method_verified'));
2020-10-28 11:10:49 +01:00
} catch (CardException $e) {
2020-06-09 14:40:55 +02:00
return back()->with('error', $e->getMessage());
}
}
public function paymentView(array $data)
{
2020-11-01 19:21:31 +01:00
$data['gateway'] = $this->stripe;
$data['currency'] = $this->stripe->client->getCurrencyCode();
$data['payment_method_id'] = GatewayType::BANK_TRANSFER;
$data['customer'] = $this->stripe->findOrCreateCustomer();
$data['amount'] = $this->stripe->convertToStripeAmount($data['total']['amount_with_fee'], $this->stripe->client->currency()->precision, $this->stripe->client->currency());
2020-06-09 14:40:55 +02:00
2020-11-01 19:21:31 +01:00
return render('gateways.stripe.ach.pay', $data);
2020-06-09 14:40:55 +02:00
}
public function tokenBilling(ClientGatewayToken $cgt, PaymentHash $payment_hash)
{
$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->stripe->client->present()->name()}";
} else {
$description = "Payment with no invoice for amount {$amount} for client {$this->stripe->client->present()->name()}";
}
$this->stripe->init();
$response = null;
try {
$state = [
'gateway_type_id' => GatewayType::BANK_TRANSFER,
'amount' => $this->stripe->convertToStripeAmount($amount, $this->stripe->client->currency()->precision, $this->stripe->client->currency()),
'currency' => $this->stripe->client->getCurrencyCode(),
'customer' => $cgt->gateway_customer_reference,
'source' => $cgt->token,
];
$state['charge'] = \Stripe\Charge::create([
'amount' => $state['amount'],
'currency' => $state['currency'],
'customer' => $state['customer'],
'source' => $state['source'],
'description' => $description,
], $this->stripe->stripe_connect_auth);
$payment_hash->data = array_merge((array)$payment_hash->data, $state);
$payment_hash->save();
if ($state['charge']->status === 'pending' && is_null($state['charge']->failure_message)) {
return $this->processPendingPayment($state, false);
}
return $this->processUnsuccessfulPayment($state);
} catch (Exception $e) {
if ($e instanceof CardException) {
2021-10-17 13:21:56 +02:00
return redirect()->route('client.payment_methods.verification', ['payment_method' => $cgt->hashed_id, 'method' => GatewayType::BANK_TRANSFER]);
}
throw new PaymentFailed($e->getMessage(), $e->getCode());
}
}
2020-11-01 19:21:31 +01:00
2020-06-09 14:40:55 +02:00
public function paymentResponse($request)
{
2021-04-20 13:30:52 +02:00
2020-11-01 19:21:31 +01:00
$this->stripe->init();
$source = ClientGatewayToken::query()
->where('id', $this->decodePrimaryKey($request->source))
->where('company_id', auth()->guard('contact')->user()->client->company->id)
->first();
if (!$source) {
throw new PaymentFailed(ctrans('texts.payment_token_not_found'), 401);
}
2020-06-09 14:40:55 +02:00
$state = [
'payment_method' => $request->payment_method_id,
'gateway_type_id' => $request->company_gateway_id,
'amount' => $this->stripe->convertToStripeAmount($request->amount, $this->stripe->client->currency()->precision, $this->stripe->client->currency()),
2020-06-09 14:40:55 +02:00
'currency' => $request->currency,
'customer' => $request->customer,
];
2020-11-01 19:21:31 +01:00
$state = array_merge($state, $request->all());
$state['source'] = $source->token;
2020-06-09 14:40:55 +02:00
$this->stripe->payment_hash->data = array_merge((array)$this->stripe->payment_hash->data, $state);
2020-11-01 19:21:31 +01:00
$this->stripe->payment_hash->save();
2020-06-09 14:40:55 +02:00
2021-11-23 18:27:45 +01:00
$amount = array_sum(array_column($this->stripe->payment_hash->invoices(), 'amount')) + $this->stripe->payment_hash->fee_total;
$invoice = Invoice::whereIn('id', $this->transformKeys(array_column($this->stripe->payment_hash->invoices(), 'invoice_id')))
->withTrashed()
->first();
if ($invoice) {
$description = "Invoice {$invoice->number} for {$amount} for client {$this->stripe->client->present()->name()}";
} else {
$description = "Payment with no invoice for amount {$amount} for client {$this->stripe->client->present()->name()}";
}
2020-06-09 14:40:55 +02:00
try {
$state['charge'] = \Stripe\Charge::create([
'amount' => $state['amount'],
'currency' => $state['currency'],
'customer' => $state['customer'],
'source' => $state['source'],
2021-11-23 18:27:45 +01:00
'description' => $description,
2021-04-20 13:30:52 +02:00
], $this->stripe->stripe_connect_auth);
2020-06-09 14:40:55 +02:00
2020-11-01 19:21:31 +01:00
$state = array_merge($state, $request->all());
$this->stripe->payment_hash->data = array_merge((array)$this->stripe->payment_hash->data, $state);
2020-11-01 19:21:31 +01:00
$this->stripe->payment_hash->save();
2020-06-09 14:40:55 +02:00
if ($state['charge']->status === 'pending' && is_null($state['charge']->failure_message)) {
return $this->processPendingPayment($state);
}
return $this->processUnsuccessfulPayment($state);
2020-10-28 11:10:49 +01:00
} catch (Exception $e) {
if ($e instanceof CardException) {
2021-08-04 04:20:38 +02:00
return redirect()->route('client.payment_methods.verification', ['payment_method' => $source->hashed_id, 'method' => GatewayType::BANK_TRANSFER]);
2020-06-09 14:40:55 +02:00
}
throw new PaymentFailed($e->getMessage(), $e->getCode());
2020-06-09 14:40:55 +02:00
}
}
public function processPendingPayment($state, $client_present = true)
2020-06-09 14:40:55 +02:00
{
$this->stripe->init();
$data = [
2020-11-01 19:21:31 +01:00
'payment_method' => $state['source'],
'payment_type' => PaymentType::ACH,
'amount' => $this->stripe->convertFromStripeAmount($this->stripe->payment_hash->data->amount, $this->stripe->client->currency()->precision, $this->stripe->client->currency()),
2020-11-01 19:21:31 +01:00
'transaction_reference' => $state['charge']->id,
2021-01-27 11:38:28 +01:00
'gateway_type_id' => GatewayType::BANK_TRANSFER,
2020-06-09 14:40:55 +02:00
];
$payment = $this->stripe->createPayment($data, Payment::STATUS_PENDING);
2020-11-01 19:21:31 +01:00
SystemLogger::dispatch(
['response' => $state['charge'], 'data' => $data],
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_SUCCESS,
SystemLog::TYPE_STRIPE,
2021-05-29 12:57:39 +02:00
$this->stripe->client,
$this->stripe->client->company,
2020-11-01 19:21:31 +01:00
);
2020-06-09 14:40:55 +02:00
if(!$client_present)
return $payment;
2020-06-09 14:40:55 +02:00
return redirect()->route('client.payments.show', ['payment' => $this->stripe->encodePrimaryKey($payment->id)]);
}
public function processUnsuccessfulPayment($state)
{
2021-10-17 12:40:40 +02:00
$this->stripe->sendFailureMail($state['charge']);
2020-11-01 19:21:31 +01:00
2020-06-09 14:40:55 +02:00
$message = [
'server_response' => $state['charge'],
2020-11-01 19:21:31 +01:00
'data' => $this->stripe->payment_hash->data,
2020-06-09 14:40:55 +02:00
];
2020-11-01 19:21:31 +01:00
SystemLogger::dispatch(
$message,
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_FAILURE,
SystemLog::TYPE_STRIPE,
$this->stripe->client
);
2020-06-09 14:40:55 +02:00
2020-11-01 19:21:31 +01:00
throw new PaymentFailed('Failed to process the payment.', 500);
2020-06-09 14:40:55 +02:00
}
private function storePaymentMethod($method, $payment_method_id, $customer)
{
try {
$payment_meta = new \stdClass;
2021-08-09 13:49:39 +02:00
$payment_meta->brand = (string) \sprintf('%s (%s)', $method->bank_name, ctrans('texts.ach'));
$payment_meta->last4 = (string) $method->last4;
$payment_meta->type = GatewayType::BANK_TRANSFER;
2021-08-09 13:49:39 +02:00
$payment_meta->state = 'unauthorized';
$data = [
'payment_meta' => $payment_meta,
'token' => $method->id,
'payment_method_id' => $payment_method_id,
];
return $this->stripe->storeGatewayToken($data, ['gateway_customer_reference' => $customer->id]);
} catch (Exception $e) {
return $this->stripe->processInternallyFailedPayment($this->stripe, $e);
}
}
2020-06-09 14:40:55 +02:00
}