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

343 lines
12 KiB
PHP
Raw Normal View History

2023-06-19 06:25:42 +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)
2023-06-19 06:25:42 +02:00
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\PaymentDrivers;
2023-10-26 04:57:44 +02:00
use App\Models\Invoice;
use App\Models\SystemLog;
use App\Models\GatewayType;
2024-03-19 02:17:25 +01:00
use Illuminate\Support\Str;
use App\Jobs\Util\SystemLogger;
2023-06-19 06:25:42 +02:00
use App\Utils\Traits\MakesHash;
use App\Exceptions\PaymentFailed;
2024-04-22 14:37:34 +02:00
use App\Models\ClientGatewayToken;
2024-05-20 03:59:44 +02:00
use App\PaymentDrivers\PayPal\PayPalBasePaymentDriver;
2023-06-19 06:25:42 +02:00
2024-05-20 03:59:44 +02:00
class PayPalRestPaymentDriver extends PayPalBasePaymentDriver
2023-06-19 06:25:42 +02:00
{
use MakesHash;
public const SYSTEM_LOG_TYPE = SystemLog::TYPE_PAYPAL;
public function processPaymentView($data)
{
2023-06-21 11:22:20 +02:00
$this->init();
2023-06-19 06:25:42 +02:00
$data['gateway'] = $this;
2024-01-14 05:05:00 +01:00
2023-06-19 06:25:42 +02:00
$this->payment_hash->data = array_merge((array) $this->payment_hash->data, ['amount' => $data['total']['amount_with_fee']]);
$this->payment_hash->save();
2023-06-21 11:22:20 +02:00
$data['client_id'] = $this->company_gateway->getConfigField('clientId');
$data['token'] = $this->getClientToken();
$data['order_id'] = $this->createOrder($data);
$data['funding_source'] = $this->paypal_payment_method;
$data['gateway_type_id'] = $this->gateway_type_id;
$data['currency'] = $this->client->currency()->code;
2023-06-20 07:51:29 +02:00
2024-05-20 05:14:50 +02:00
if($this->gateway_type_id == 29)
2024-05-20 03:59:44 +02:00
return render('gateways.paypal.ppcp.card', $data);
else
return render('gateways.paypal.pay', $data);
2024-04-22 06:38:29 +02:00
}
2024-05-20 03:59:44 +02:00
/**
* processPaymentResponse
*
* @param mixed $request
* @return void
*/
2023-06-21 11:22:20 +02:00
public function processPaymentResponse($request)
{
2023-07-23 04:43:23 +02:00
$this->init();
$request['gateway_response'] = str_replace("Error: ", "", $request['gateway_response']);
2023-06-21 11:22:20 +02:00
$response = json_decode($request['gateway_response'], true);
2024-03-19 02:17:25 +01:00
2024-05-24 02:38:07 +02:00
nlog($response);
2024-04-22 14:37:34 +02:00
if($request->has('token') && strlen($request->input('token')) > 2)
return $this->processTokenPayment($request, $response);
2024-04-22 06:38:29 +02:00
//capture
$orderID = $response['orderID'];
if($this->company_gateway->require_shipping_address) {
$shipping_data =
[[
"op" => "replace",
"path" => "/purchase_units/@reference_id=='default'/shipping/address",
"value" => [
"address_line_1" => strlen($this->client->shipping_address1) > 1 ? $this->client->shipping_address1 : $this->client->address1,
"address_line_2" => $this->client->shipping_address2,
"admin_area_2" => strlen($this->client->shipping_city) > 1 ? $this->client->shipping_city : $this->client->city,
"admin_area_1" => strlen($this->client->shipping_state) > 1 ? $this->client->shipping_state : $this->client->state,
"postal_code" => strlen($this->client->shipping_postal_code) > 1 ? $this->client->shipping_postal_code : $this->client->postal_code,
"country_code" => $this->client->present()->shipping_country_code(),
],
]];
$r = $this->gatewayRequest("/v2/checkout/orders/{$orderID}", 'patch', $shipping_data);
}
2024-03-19 02:17:25 +01:00
try{
2024-05-24 02:38:07 +02:00
2024-03-19 02:17:25 +01:00
$r = $this->gatewayRequest("/v2/checkout/orders/{$orderID}/capture", 'post', ['body' => '']);
2024-05-24 02:38:07 +02:00
if($r->status() == 422){
//handle conditions where the client may need to try again.
return $this->handleRetry($r, $request);
}
2024-03-19 02:17:25 +01:00
}
catch(\Exception $e) {
//Rescue for duplicate invoice_id
if(stripos($e->getMessage(), 'DUPLICATE_INVOICE_ID') !== false){
$_invoice = collect($this->payment_hash->data->invoices)->first();
$invoice = Invoice::withTrashed()->find($this->decodePrimaryKey($_invoice->invoice_id));
$new_invoice_number = $invoice->number."_".Str::random(5);
$update_data =
[[
"op" => "replace",
"path" => "/purchase_units/@reference_id=='default'/invoice_id",
"value" => $new_invoice_number,
]];
$r = $this->gatewayRequest("/v2/checkout/orders/{$orderID}", 'patch', $update_data);
$r = $this->gatewayRequest("/v2/checkout/orders/{$orderID}/capture", 'post', ['body' => '']);
}
}
$response = $r;
2024-05-20 05:14:50 +02:00
nlog("Process response =>");
nlog($response->json());
if(isset($response['status']) && $response['status'] == 'COMPLETED' && isset($response['purchase_units'])) {
2023-06-21 13:11:41 +02:00
2024-04-22 14:37:34 +02:00
return $this->createNinjaPayment($request, $response);
2023-06-21 13:11:41 +02:00
2023-10-26 04:57:44 +02:00
} else {
2023-07-23 04:43:23 +02:00
if(isset($response['headers']) ?? false) {
unset($response['headers']);
}
2023-07-23 04:43:23 +02:00
SystemLogger::dispatch(
['response' => $response],
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_FAILURE,
SystemLog::TYPE_PAYPAL,
$this->client,
$this->client->company,
);
$message = $response['body']['details'][0]['description'] ?? 'Payment failed. Please try again.';
2023-07-23 04:43:23 +02:00
2024-05-24 02:38:07 +02:00
return response()->json(['message' => $message], 400);
//throw new PaymentFailed($message, 400);
2023-06-21 13:11:41 +02:00
}
2023-06-21 11:22:20 +02:00
}
2024-04-22 14:37:34 +02:00
private function createNinjaPayment($request, $response) {
$data = [
'payment_type' => $this->getPaymentMethod($request->gateway_type_id),
'amount' => $response['purchase_units'][0]['payments']['captures'][0]['amount']['value'],
'transaction_reference' => $response['purchase_units'][0]['payments']['captures'][0]['id'],
'gateway_type_id' => GatewayType::PAYPAL,
];
$payment = $this->createPayment($data, \App\Models\Payment::STATUS_COMPLETED);
if ($request->has('store_card') && $request->input('store_card') === true) {
$payment_source = $response->json()['payment_source'];
if(isset($payment_source['card']) && ($payment_source['card']['attributes']['vault']['status'] ?? false) && $payment_source['card']['attributes']['vault']['status'] == 'VAULTED') {
$last4 = $payment_source['card']['last_digits'];
$expiry = $payment_source['card']['expiry']; //'2025-01'
$expiry_meta = explode('-', $expiry);
$brand = $payment_source['card']['brand'];
$payment_meta = new \stdClass();
$payment_meta->exp_month = $expiry_meta[1] ?? '';
$payment_meta->exp_year = $expiry_meta[0] ?? $expiry;
$payment_meta->brand = $brand;
$payment_meta->last4 = $last4;
$payment_meta->type = GatewayType::CREDIT_CARD;
$token = $payment_source['card']['attributes']['vault']['id']; // 09f28652d01257021
$gateway_customer_reference = $payment_source['card']['attributes']['vault']['customer']['id']; //rbTHnLsZqE;
$data['token'] = $token;
$data['payment_method_id'] = GatewayType::PAYPAL_ADVANCED_CARDS;
$data['payment_meta'] = $payment_meta;
$additional['gateway_customer_reference'] = $gateway_customer_reference;
$this->storeGatewayToken($data, $additional);
}
}
SystemLogger::dispatch(
['response' => $response->json(), 'data' => $data],
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_SUCCESS,
SystemLog::TYPE_PAYPAL,
$this->client,
$this->client->company,
);
2024-05-24 02:38:07 +02:00
return response()->json(['redirect' => route('client.payments.show', ['payment' => $this->encodePrimaryKey($payment->id)], false)]);
// return redirect()->route('client.payments.show', ['payment' => $this->encodePrimaryKey($payment->id)]);
2024-04-22 14:37:34 +02:00
}
2024-05-20 03:59:44 +02:00
public function createOrder(array $data): string
2023-06-21 11:22:20 +02:00
{
$_invoice = collect($this->payment_hash->data->invoices)->first();
$invoice = Invoice::withTrashed()->find($this->decodePrimaryKey($_invoice->invoice_id));
$description = collect($invoice->line_items)->map(function ($item) {
return $item->notes;
})->implode("\n");
2023-06-21 11:22:20 +02:00
$order = [
"intent" => "CAPTURE",
2024-04-16 14:01:25 +02:00
"payment_source" => $this->getPaymentSource(),
"purchase_units" => [
[
"custom_id" => $this->payment_hash->hash,
"description" => ctrans('texts.invoice_number') . '# ' . $invoice->number,
"invoice_id" => $invoice->number,
"amount" => [
"value" => (string) $data['amount_with_fee'],
2023-06-21 11:22:20 +02:00
"currency_code" => $this->client->currency()->code,
"breakdown" => [
"item_total" => [
"currency_code" => $this->client->currency()->code,
"value" => (string) $data['amount_with_fee']
]
]
],
"items" => [
[
"name" => ctrans('texts.invoice_number') . '# ' . $invoice->number,
"description" => mb_substr($description, 0, 127),
"quantity" => "1",
"unit_amount" => [
"currency_code" => $this->client->currency()->code,
"value" => (string) $data['amount_with_fee']
],
],
2023-06-21 11:22:20 +02:00
],
],
]
];
if($shipping = $this->getShippingAddress()) {
$order['purchase_units'][0]["shipping"] = $shipping;
}
2024-01-14 05:05:00 +01:00
2024-04-22 14:37:34 +02:00
if(isset($data['payment_source']))
$order['payment_source'] = $data['payment_source'];
2024-05-20 03:59:44 +02:00
2023-06-21 11:22:20 +02:00
$r = $this->gatewayRequest('/v2/checkout/orders', 'post', $order);
2023-06-20 07:51:29 +02:00
2024-05-24 02:38:07 +02:00
nlog($r->json());
2023-06-21 11:22:20 +02:00
return $r->json()['id'];
2023-06-19 06:25:42 +02:00
}
/**
2024-05-20 03:59:44 +02:00
* processTokenPayment
*
2024-05-20 03:59:44 +02:00
* With PayPal and token payments, the order needs to be
* deleted and then created with the payment source that
* has been selected by the client.
*
* This method handle the deletion of the current paypal order,
* and the automatic payment of the order with the selected payment source.
*
* @param mixed $request
* @param array $response
* @return void
*/
2024-05-20 03:59:44 +02:00
public function processTokenPayment($request, array $response) {
2024-05-20 03:59:44 +02:00
$cgt = ClientGatewayToken::where('client_id', $this->client->id)
->where('token', $request['token'])
->firstOrFail();
2023-06-21 11:22:20 +02:00
2024-05-20 03:59:44 +02:00
$orderId = $response['orderID'];
$r = $this->gatewayRequest("/v1/checkout/orders/{$orderId}/", 'delete', ['body' => '']);
$data['amount_with_fee'] = $this->payment_hash->data->amount_with_fee;
$data["payment_source"] = [
"card" => [
"vault_id" => $cgt->token,
"stored_credential" => [
"payment_initiator" => "MERCHANT",
"payment_type" => "UNSCHEDULED",
"usage" => "SUBSEQUENT",
],
],
];
$orderId = $this->createOrder($data);
$r = $this->gatewayRequest("/v2/checkout/orders/{$orderId}", 'get', ['body' => '']);
$response = $r->json();
$data = [
'payment_type' => $this->getPaymentMethod($request->gateway_type_id),
'amount' => $response['purchase_units'][0]['payments']['captures'][0]['amount']['value'],
'transaction_reference' => $response['purchase_units'][0]['payments']['captures'][0]['id'],
'gateway_type_id' => $this->gateway_type_id,
];
$payment = $this->createPayment($data, \App\Models\Payment::STATUS_COMPLETED);
2023-06-21 11:22:20 +02:00
SystemLogger::dispatch(
2024-05-20 03:59:44 +02:00
['response' => $response, 'data' => $data],
SystemLog::CATEGORY_GATEWAY_RESPONSE,
2024-05-20 03:59:44 +02:00
SystemLog::EVENT_GATEWAY_SUCCESS,
SystemLog::TYPE_PAYPAL,
$this->client,
2024-05-20 03:59:44 +02:00
$this->client->company,
);
2024-05-20 03:59:44 +02:00
return redirect()->route('client.payments.show', ['payment' => $this->encodePrimaryKey($payment->id)]);
2024-03-16 02:36:40 +01:00
}
2023-06-19 06:25:42 +02:00
}