1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-15 23:52:33 +01:00
invoiceninja/app/PaymentDrivers/SquarePaymentDriver.php

639 lines
20 KiB
PHP
Raw Normal View History

2021-08-14 10:11:45 +02:00
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
2024-04-12 06:15:41 +02:00
* @copyright Copyright (c) 2024. Invoice Ninja LLC (https://invoiceninja.com)
2021-08-14 10:11:45 +02:00
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\PaymentDrivers;
2021-08-19 13:50:34 +02:00
use App\Models\Invoice;
2021-08-14 10:11:45 +02:00
use App\Models\Payment;
2024-03-19 00:38:54 +01:00
use App\Models\SystemLog;
use App\Models\GatewayType;
2021-08-14 10:11:45 +02:00
use App\Models\PaymentHash;
2021-08-19 13:50:34 +02:00
use App\Models\PaymentType;
2024-03-19 00:38:54 +01:00
use App\Models\ClientContact;
use App\Factory\ClientFactory;
use App\Jobs\Util\SystemLogger;
use App\Utils\Traits\MakesHash;
use Square\Utils\WebhooksHelper;
use App\Models\ClientGatewayToken;
use App\Repositories\ClientRepository;
use Square\Models\WebhookSubscription;
2023-08-19 03:13:52 +02:00
use App\PaymentDrivers\Square\CreditCard;
2023-08-19 04:23:37 +02:00
use App\PaymentDrivers\Square\SquareWebhook;
2024-03-19 00:38:54 +01:00
use App\Repositories\ClientContactRepository;
2023-10-26 04:57:44 +02:00
use Square\Models\CreateWebhookSubscriptionRequest;
2024-03-19 00:38:54 +01:00
use App\Http\Requests\Payments\PaymentWebhookRequest;
use App\PaymentDrivers\Factory\SquareCustomerFactory;
use Square\Models\Builders\RefundPaymentRequestBuilder;
2021-08-14 10:11:45 +02:00
class SquarePaymentDriver extends BaseDriver
{
use MakesHash;
2021-08-21 14:22:22 +02:00
public $refundable = false; //does this gateway support refunds?
2021-08-14 10:11:45 +02:00
public $token_billing = true; //does this gateway support token billing?
public $can_authorise_credit_card = true; //does this gateway support authorizations?
2021-08-19 13:50:34 +02:00
public $square;
2021-08-14 10:11:45 +02:00
2021-08-14 11:32:16 +02:00
public $payment_method;
2021-08-14 10:11:45 +02:00
public static $methods = [
GatewayType::CREDIT_CARD => CreditCard::class, //maps GatewayType => Implementation class
];
2024-01-14 05:05:00 +01:00
public const SYSTEM_LOG_TYPE = SystemLog::TYPE_SQUARE;
2021-08-14 10:11:45 +02:00
public function init()
{
2021-08-14 13:37:04 +02:00
$this->square = new \Square\SquareClient([
2021-08-14 11:32:16 +02:00
'accessToken' => $this->company_gateway->getConfigField('accessToken'),
2021-08-14 13:37:04 +02:00
'environment' => $this->company_gateway->getConfigField('testMode') ? \Square\Environment::SANDBOX : \Square\Environment::PRODUCTION,
2021-08-14 10:11:45 +02:00
]);
return $this; /* This is where you boot the gateway with your auth credentials*/
}
/* Returns an array of gateway types for the payment gateway */
public function gatewayTypes(): array
{
$types = [];
2021-08-19 13:50:34 +02:00
$types[] = GatewayType::CREDIT_CARD;
2021-08-14 10:11:45 +02:00
return $types;
}
/* Sets the payment method initialized */
public function setPaymentMethod($payment_method_id)
{
$class = self::$methods[$payment_method_id];
$this->payment_method = new $class($this);
2021-08-14 10:11:45 +02:00
return $this;
}
public function authorizeView(array $data)
{
return $this->payment_method->authorizeView($data); //this is your custom implementation from here
}
public function authorizeResponse($request)
{
return $this->payment_method->authorizeResponse($request); //this is your custom implementation from here
}
public function processPaymentView(array $data)
{
return $this->payment_method->paymentView($data); //this is your custom implementation from here
}
public function processPaymentResponse($request)
{
return $this->payment_method->paymentResponse($request); //this is your custom implementation from here
}
public function refund(Payment $payment, $amount, $return_client_response = false)
{
2021-08-19 14:05:11 +02:00
$this->init();
2023-08-19 03:13:52 +02:00
$this->client = $payment->client;
2021-08-19 14:05:11 +02:00
$amount_money = new \Square\Models\Money();
$amount_money->setAmount($this->convertAmount($amount));
2023-02-03 02:35:36 +01:00
$amount_money->setCurrency($this->client->currency()->code);
2021-08-19 14:05:11 +02:00
2023-08-19 03:13:52 +02:00
$body = RefundPaymentRequestBuilder::init(\Illuminate\Support\Str::random(32), $amount_money)
->paymentId($payment->transaction_reference)
->reason('Refund Request')
->build();
$apiResponse = $this->square->getRefundsApi()->refundPayment($body);
if ($apiResponse->isSuccess()) {
$refundPaymentResponse = $apiResponse->getResult();
nlog($refundPaymentResponse);
/**
* - `PENDING` - Awaiting approval.
* - `COMPLETED` - Successfully completed.
* - `REJECTED` - The refund was rejected.
* - `FAILED` - An error occurred.
*/
$status = $refundPaymentResponse->getRefund()->getStatus();
2023-10-26 04:57:44 +02:00
if(in_array($status, ['COMPLETED', 'PENDING'])) {
2023-08-19 03:13:52 +02:00
$transaction_reference = $refundPaymentResponse->getRefund()->getId();
$data = [
'transaction_reference' => $transaction_reference,
'transaction_response' => json_encode($refundPaymentResponse->getRefund()->jsonSerialize()),
'success' => true,
'description' => $refundPaymentResponse->getRefund()->getReason(),
'code' => $refundPaymentResponse->getRefund()->getReason(),
];
SystemLogger::dispatch(
[
'server_response' => $data,
'data' => request()->all()
],
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_SUCCESS,
SystemLog::TYPE_SQUARE,
$this->client,
$this->client->company
);
return $data;
2023-10-26 04:57:44 +02:00
} elseif(in_array($status, ['REJECTED', 'FAILED'])) {
2023-08-19 03:13:52 +02:00
$transaction_reference = $refundPaymentResponse->getRefund()->getId();
$data = [
'transaction_reference' => $transaction_reference,
'transaction_response' => json_encode($refundPaymentResponse->getRefund()->jsonSerialize()),
'success' => false,
'description' => $refundPaymentResponse->getRefund()->getReason(),
'code' => $refundPaymentResponse->getRefund()->getReason(),
];
SystemLogger::dispatch(
[
'server_response' => $data,
'data' => request()->all()
],
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_FAILURE,
SystemLog::TYPE_SQUARE,
$this->client,
$this->client->company
);
return $data;
}
} else {
2024-01-14 05:05:00 +01:00
2023-08-19 03:13:52 +02:00
/** @var \Square\Models\Error $error */
$error = end($apiResponse->getErrors());
$data = [
'transaction_reference' => $payment->transaction_reference,
'transaction_response' => $error->jsonSerialize(),
'success' => false,
'description' => $error->getDetail(),
'code' => $error->getCode(),
];
2023-10-26 04:57:44 +02:00
SystemLogger::dispatch(
[
'server_response' => $data,
'data' => request()->all()
],
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_FAILURE,
SystemLog::TYPE_SQUARE,
$this->client,
$this->client->company
);
2023-08-19 03:13:52 +02:00
return $data;
}
2021-08-19 14:05:11 +02:00
2021-08-14 10:11:45 +02:00
}
public function tokenBilling(ClientGatewayToken $cgt, PaymentHash $payment_hash)
{
2021-08-19 13:50:34 +02:00
$this->init();
$amount = array_sum(array_column($payment_hash->invoices(), 'amount')) + $payment_hash->fee_total;
$amount = $this->convertAmount($amount);
2023-08-06 09:03:12 +02:00
$invoice = Invoice::query()->whereIn('id', $this->transformKeys(array_column($payment_hash->invoices(), 'invoice_id')))->withTrashed()->first();
2021-08-19 13:50:34 +02:00
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()}";
}
$amount_money = new \Square\Models\Money();
$amount_money->setAmount($amount);
$amount_money->setCurrency($this->client->currency()->code);
2023-08-20 11:17:21 +02:00
$body = new \Square\Models\CreatePaymentRequest($cgt->token, \Illuminate\Support\Str::random(32));
2021-11-27 01:46:28 +01:00
$body->setCustomerId($cgt->gateway_customer_reference);
2023-08-19 02:39:24 +02:00
$body->setAmountMoney($amount_money);
2023-08-19 04:23:37 +02:00
$body->setReferenceId($payment_hash->hash);
2023-10-26 04:57:44 +02:00
$body->setNote(substr($description, 0, 500));
2021-08-19 13:50:34 +02:00
$response = $this->square->getPaymentsApi()->createPayment($body);
$body = json_decode($response->getBody());
if ($response->isSuccess()) {
$amount = array_sum(array_column($this->payment_hash->invoices(), 'amount')) + $this->payment_hash->fee_total;
$payment_record = [];
$payment_record['amount'] = $amount;
$payment_record['payment_type'] = PaymentType::CREDIT_CARD_OTHER;
$payment_record['gateway_type_id'] = GatewayType::CREDIT_CARD;
$payment_record['transaction_reference'] = $body->payment->id;
$payment = $this->createPayment($payment_record, Payment::STATUS_COMPLETED);
SystemLogger::dispatch(
['response' => $response, 'data' => $payment_record],
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_SUCCESS,
SystemLog::TYPE_CHECKOUT,
$this->client,
$this->client->company,
);
return $payment;
}
$this->unWindGatewayFees($payment_hash);
2021-10-17 12:40:40 +02:00
$this->sendFailureMail($body->errors[0]->detail);
2021-08-19 13:50:34 +02:00
$message = [
'server_response' => $response,
'data' => $payment_hash->data,
];
SystemLogger::dispatch(
$message,
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_FAILURE,
SystemLog::TYPE_SQUARE,
$this->client,
$this->client->company,
);
return false;
2021-08-14 10:11:45 +02:00
}
2023-08-20 11:59:59 +02:00
public function checkWebhooks(): mixed
2023-08-19 07:52:37 +02:00
{
$this->init();
2024-01-14 05:05:00 +01:00
2023-08-19 07:52:37 +02:00
$api_response = $this->square->getWebhookSubscriptionsApi()->listWebhookSubscriptions();
if ($api_response->isSuccess()) {
2024-01-14 05:05:00 +01:00
2023-08-19 07:52:37 +02:00
//array of WebhookSubscription objects
2023-10-26 04:57:44 +02:00
foreach($api_response->getResult()->getSubscriptions() ?? [] as $subscription) {
if($subscription->getName() == 'Invoice_Ninja_Webhook_Subscription') {
return $subscription->getId();
}
2023-08-19 07:52:37 +02:00
}
2024-01-14 05:05:00 +01:00
2023-08-19 07:52:37 +02:00
} else {
$errors = $api_response->getErrors();
nlog($errors);
2023-08-20 12:33:41 +02:00
return false;
2023-08-19 07:52:37 +02:00
}
return false;
}
// {
// "subscription": {
// "id": "wbhk_b35f6b3145074cf9ad513610786c19d5",
// "name": "Example Webhook Subscription",
// "enabled": true,
// "event_types": [
// "payment.created",
// "order.updated",
// "invoice.created"
// ],
// "notification_url": "https://example-webhook-url.com",
// "api_version": "2021-12-15",
// "signature_key": "1k9bIJKCeTmSQwyagtNRLg",
// "created_at": "2022-08-17 23:29:48 +0000 UTC",
// "updated_at": "2022-08-17 23:29:48 +0000 UTC"
// }
// }
public function createWebhooks(): void
2023-08-19 02:14:46 +02:00
{
2024-01-14 05:05:00 +01:00
2023-10-26 04:57:44 +02:00
if($this->checkWebhooks()) {
2023-08-19 07:52:37 +02:00
return;
2023-10-26 04:57:44 +02:00
}
2023-08-19 07:52:37 +02:00
2023-08-19 02:14:46 +02:00
$this->init();
$event_types = ['payment.created', 'payment.updated'];
2023-08-19 04:23:37 +02:00
$subscription = new WebhookSubscription();
$subscription->setName('Invoice_Ninja_Webhook_Subscription');
2023-08-19 02:14:46 +02:00
$subscription->setEventTypes($event_types);
2023-08-19 07:52:37 +02:00
2023-08-19 08:32:24 +02:00
// $subscription->setNotificationUrl('https://invoicing.co');
2023-08-19 07:52:37 +02:00
2023-08-19 08:32:24 +02:00
$subscription->setNotificationUrl($this->company_gateway->webhookUrl());
2023-08-19 02:14:46 +02:00
// $subscription->setApiVersion('2021-12-15');
2023-08-19 04:23:37 +02:00
$body = new CreateWebhookSubscriptionRequest($subscription);
2023-08-19 02:14:46 +02:00
$body->setIdempotencyKey(\Illuminate\Support\Str::uuid());
$api_response = $this->square->getWebhookSubscriptionsApi()->createWebhookSubscription($body);
if ($api_response->isSuccess()) {
2023-08-19 07:52:37 +02:00
$subscription = $api_response->getResult()->getSubscription();
$signatureKey = $subscription->getSignatureKey();
2023-08-19 08:32:24 +02:00
2023-08-19 07:52:37 +02:00
$this->company_gateway->setConfigField('signatureKey', $signatureKey);
2024-01-14 05:05:00 +01:00
2023-08-19 02:14:46 +02:00
} else {
$errors = $api_response->getErrors();
2023-08-19 07:52:37 +02:00
nlog($errors);
2023-08-19 02:14:46 +02:00
}
}
2023-08-19 04:23:37 +02:00
public function processWebhookRequest(PaymentWebhookRequest $request)
2021-08-14 10:11:45 +02:00
{
2023-08-20 13:33:23 +02:00
nlog("square webhook");
2023-08-19 04:23:37 +02:00
$signature_key = $this->company_gateway->getConfigField('signatureKey');
$notification_url = $this->company_gateway->webhookUrl();
2023-08-19 02:14:46 +02:00
2023-10-26 04:57:44 +02:00
$body = '';
2023-08-19 04:23:37 +02:00
$handle = fopen('php://input', 'r');
while(!feof($handle)) {
$body .= fread($handle, 1024);
}
2023-08-19 02:14:46 +02:00
2023-08-19 04:23:37 +02:00
if (WebhooksHelper::isValidWebhookEventSignature($body, $request->header('x-square-hmacsha256-signature'), $signature_key, $notification_url)) {
SquareWebhook::dispatch($request->all(), $request->company_key, $this->company_gateway->id)->delay(5);
} else {
nlog("Square Hash Mismatch");
nlog($request->all());
}
2023-08-19 02:14:46 +02:00
2023-08-19 04:23:37 +02:00
return response()->json(['success' => true]);
2023-08-19 02:14:46 +02:00
2021-08-14 10:11:45 +02:00
}
2021-08-16 03:11:08 +02:00
2023-08-20 11:20:12 +02:00
public function testWebhook()
{
$this->init();
$body = new \Square\Models\TestWebhookSubscriptionRequest();
$body->setEventType('payment.created');
//getsubscriptionid here
2023-08-20 11:59:59 +02:00
$subscription_id = $this->checkWebhooks();
2023-08-20 11:20:12 +02:00
2023-10-26 04:57:44 +02:00
if(!$subscription_id) {
nlog('No Subscription Found');
2023-08-23 07:03:48 +02:00
return;
}
2023-08-20 11:59:59 +02:00
$api_response = $this->square->getWebhookSubscriptionsApi()->testWebhookSubscription($subscription_id, $body);
2023-08-20 11:20:12 +02:00
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
nlog($result);
} else {
$errors = $api_response->getErrors();
nlog($errors);
}
}
2021-08-21 14:22:22 +02:00
public function convertAmount($amount)
2021-08-19 13:50:34 +02:00
{
$precision = $this->client->currency()->precision;
if ($precision == 0) {
return $amount;
}
if ($precision == 1) {
return $amount * 10;
2021-08-19 13:50:34 +02:00
}
if ($precision == 2) {
return $amount * 100;
2021-08-19 13:50:34 +02:00
}
return $amount;
}
2024-03-16 02:36:40 +01:00
public function auth(): bool
{
$api_response = $this->init()
->square
->getCustomersApi()
->listCustomers();
return (bool) count($api_response->getErrors()) == 0;
}
2024-03-19 00:38:54 +01:00
public function importCustomers()
{
$limit = 100;
$api_response = $this->init()
->square
->getCustomersApi()
->listCustomers(null,
$limit,
'DEFAULT',
'DESC'
);
if ($api_response->isSuccess()) {
while ($api_response->getResult()->getCustomers()) {
$customers = $api_response->getResult()->getCustomers();
$client_repo = new ClientRepository(new ClientContactRepository());
foreach($customers as $customer)
{
$data = (new SquareCustomerFactory())->convertToNinja($customer, $this->company_gateway->company);
$client = ClientContact::where('company_id', $this->company_gateway->company_id)->where('email', $customer->getEmailAddress())->first()->client ?? false;
if(!$client)
$client = $client_repo->save($data, ClientFactory::create($this->company_gateway->company_id, $this->company_gateway->user_id));
$this->client = $client;
foreach($data['cards'] as $card) {
if(ClientGatewayToken::where('company_id', $this->company_gateway->company_id)->where('token', $card['token'])->exists())
continue;
$this->storeGatewayToken($card);
}
}
$c = $api_response->getCursor();
if ($c) {
2024-03-19 00:40:11 +01:00
$api_response = $this->init()
->square
->getCustomersApi()
->listCustomers(
$c,
$limit,
'DEFAULT',
'DESC'
);
2024-03-19 00:38:54 +01:00
} else {
break;
}
}
}
}
private function findClient($email = null)
{
$email_address_string = $email ?? $this->client->present()->email();
$email_address = new \Square\Models\CustomerTextFilter();
$email_address->setExact($email_address_string);
$filter = new \Square\Models\CustomerFilter();
$filter->setEmailAddress($email_address);
$query = new \Square\Models\CustomerQuery();
$query->setFilter($filter);
$body = new \Square\Models\SearchCustomersRequest();
$body->setQuery($query);
$api_response = $this->init()
->square
->getCustomersApi()
->searchCustomers($body);
$customers = false;
if ($api_response->isSuccess()) {
$customers = $api_response->getBody();
$customers = json_decode($customers);
if (count([$api_response->getBody(), 1]) == 0) {
$customers = false;
}
} else {
$errors = $api_response->getErrors();
}
if ($customers && property_exists($customers, 'customers')) {
return $customers->customers[0]->id;
}
return false;
}
public function findOrCreateClient()
{
if($customer_id = $this->findClient())
return $customer_id;
return $this->createClient();
}
private function createClient()
{
$country = $this->client->country ? $this->client->country->iso_3166_2 : $this->client->company->country()->iso_3166_2;
/* Step two - create the customer */
$billing_address = new \Square\Models\Address();
$billing_address->setAddressLine1($this->client->address1);
$billing_address->setAddressLine2($this->client->address2);
$billing_address->setLocality($this->client->city);
$billing_address->setAdministrativeDistrictLevel1($this->client->state);
$billing_address->setPostalCode($this->client->postal_code);
$billing_address->setCountry($country);
$body = new \Square\Models\CreateCustomerRequest();
$body->setGivenName($this->client->present()->name());
$body->setFamilyName('');
$body->setEmailAddress($this->client->present()->email());
$body->setAddress($billing_address);
$body->setReferenceId($this->client->number);
$body->setNote('Created by Invoice Ninja.');
$api_response = $this->init()
->square
->getCustomersApi()
->createCustomer($body);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
return $result->getCustomer()->getId();
} else {
$errors = $api_response->getErrors();
nlog($errors);
$error = end($errors);
$data = [
'response' => $error->getDetail(),
'error' => $error->getDetail(),
'error_code' => $error->getCode(),
];
return $this->processUnsuccessfulTransaction($data);
}
}
2021-08-19 13:50:34 +02:00
}