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

554 lines
18 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;
use Carbon\Carbon;
use Omnipay\Omnipay;
2023-10-26 04:57:44 +02:00
use App\Models\Invoice;
use App\Models\SystemLog;
use App\Models\GatewayType;
use App\Models\PaymentType;
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;
2023-06-20 06:25:42 +02:00
use Illuminate\Support\Facades\Http;
2023-06-19 06:25:42 +02:00
2023-06-20 14:39:55 +02:00
class PayPalRestPaymentDriver extends BaseDriver
2023-06-19 06:25:42 +02:00
{
use MakesHash;
public $token_billing = false;
public $can_authorise_credit_card = false;
private $omnipay_gateway;
private float $fee = 0;
public const SYSTEM_LOG_TYPE = SystemLog::TYPE_PAYPAL;
2023-06-21 11:22:20 +02:00
private string $api_endpoint_url = '';
2023-07-23 01:32:05 +02:00
private string $paypal_payment_method = '';
private ?int $gateway_type_id = null;
2024-02-13 05:25:18 +01:00
protected mixed $access_token = null;
protected ?Carbon $token_expiry = null;
2023-07-23 01:32:05 +02:00
private array $funding_options = [
3 => 'paypal',
1 => 'card',
25 => 'venmo',
2023-08-01 15:53:10 +02:00
// 9 => 'sepa',
// 12 => 'bancontact',
// 17 => 'eps',
// 15 => 'giropay',
// 13 => 'ideal',
// 26 => 'mercadopago',
// 27 => 'mybank',
28 => 'paylater',
2023-08-01 15:53:10 +02:00
// 16 => 'p24',
// 7 => 'sofort'
2023-07-23 01:32:05 +02:00
];
2023-06-19 06:25:42 +02:00
public function gatewayTypes()
{
2023-06-23 15:04:14 +02:00
$funding_options = [];
foreach ($this->company_gateway->fees_and_limits as $key => $value) {
if ($value->is_enabled) {
$funding_options[] = $key;
}
}
2023-07-23 01:32:05 +02:00
return $funding_options;
2023-06-23 15:04:14 +02:00
2023-06-19 06:25:42 +02:00
}
public function init()
{
2023-06-20 14:39:55 +02:00
2023-06-21 11:22:20 +02:00
$this->api_endpoint_url = $this->company_gateway->getConfigField('testMode') ? 'https://api-m.sandbox.paypal.com' : 'https://api-m.paypal.com';
2024-01-14 05:05:00 +01:00
$secret = $this->company_gateway->getConfigField('secret');
$client_id = $this->company_gateway->getConfigField('clientId');
if($this->access_token && $this->token_expiry && $this->token_expiry->isFuture()) {
return $this;
}
$response = Http::withBasicAuth($client_id, $secret)
->withHeaders(['Content-Type' => 'application/x-www-form-urlencoded'])
->withQueryParameters(['grant_type' => 'client_credentials'])
->post("{$this->api_endpoint_url}/v1/oauth2/token");
if($response->successful()) {
$this->access_token = $response->json()['access_token'];
$this->token_expiry = now()->addSeconds($response->json()['expires_in'] - 60);
} else {
throw new PaymentFailed('Unable to gain access token from Paypal. Check your configuration', 401);
}
2023-06-20 14:39:55 +02:00
return $this;
}
private function getPaymentMethod($gateway_type_id): int
{
$method = PaymentType::PAYPAL;
match($gateway_type_id) {
"1" => $method = PaymentType::CREDIT_CARD_OTHER,
"3" => $method = PaymentType::PAYPAL,
"25" => $method = PaymentType::VENMO,
"28" => $method = PaymentType::PAY_LATER,
};
return $method;
2023-06-19 06:25:42 +02:00
}
public function setPaymentMethod($payment_method_id): self
2023-06-19 06:25:42 +02:00
{
2023-10-26 04:57:44 +02:00
if(!$payment_method_id) {
2023-07-23 04:43:23 +02:00
return $this;
2023-10-26 04:57:44 +02:00
}
2023-07-23 04:43:23 +02:00
$this->gateway_type_id = $payment_method_id;
2023-07-23 01:32:05 +02:00
$this->paypal_payment_method = $this->funding_options[$payment_method_id];
2023-06-19 06:25:42 +02:00
return $this;
}
public function authorizeView($payment_method)
{
// PayPal doesn't support direct authorization.
return $this;
}
public function authorizeResponse($request)
{
// PayPal doesn't support direct authorization.
return $this;
}
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-04-15 05:42:44 +02:00
2024-04-16 23:35:41 +02:00
// return render('gateways.paypal.ppcp.card', $data);
2024-04-15 05:42:44 +02:00
2024-04-16 23:35:41 +02:00
return render('gateways.paypal.pay', $data);
2023-06-21 11:22:20 +02:00
}
2024-01-14 05:05:00 +01:00
private function getFundingOptions(): string
2023-06-23 12:05:36 +02:00
{
2023-06-23 15:04:14 +02:00
$enums = [
2023-10-26 04:57:44 +02:00
3 => 'paypal',
1 => 'card',
25 => 'venmo',
// 9 => 'sepa',
// 12 => 'bancontact',
// 17 => 'eps',
// 15 => 'giropay',
// 13 => 'ideal',
// 26 => 'mercadopago',
// 27 => 'mybank',
// 28 => 'paylater',
// 16 => 'p24',
2023-07-23 01:32:05 +02:00
// 7 => 'sofort'
2023-06-23 15:04:14 +02:00
];
$funding_options = '';
foreach($this->company_gateway->fees_and_limits as $key => $value) {
if($value->is_enabled) {
2024-01-14 05:05:00 +01:00
$funding_options .= $enums[$key].',';
2023-06-23 15:04:14 +02:00
}
}
return rtrim($funding_options, ',');
2023-06-23 12:05:36 +02:00
}
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-03-19 03:16:20 +01:00
// nlog($response);
//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{
$r = $this->gatewayRequest("/v2/checkout/orders/{$orderID}/capture", 'post', ['body' => '']);
}
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;
if(isset($response['status']) && $response['status'] == 'COMPLETED' && isset($response['purchase_units'])) {
2023-06-21 13:11:41 +02:00
$data = [
'payment_type' => $this->getPaymentMethod($request->gateway_type_id),
'amount' => $response['purchase_units'][0]['payments']['captures'][0]['amount']['value'],
2023-06-21 13:11:41 +02:00
'transaction_reference' => $response['purchase_units'][0]['payments']['captures'][0]['id'],
'gateway_type_id' => GatewayType::PAYPAL,
];
$payment = $this->createPayment($data, \App\Models\Payment::STATUS_COMPLETED);
SystemLogger::dispatch(
['response' => $response, 'data' => $data],
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_SUCCESS,
SystemLog::TYPE_PAYPAL,
$this->client,
$this->client->company,
);
return redirect()->route('client.payments.show', ['payment' => $this->encodePrimaryKey($payment->id)]);
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
throw new PaymentFailed($message, 400);
2023-06-21 13:11:41 +02:00
}
2023-06-21 11:22:20 +02:00
}
private function getClientToken(): string
{
$r = $this->gatewayRequest('/v1/identity/generate-token', 'post', ['body' => '']);
2023-10-26 04:57:44 +02:00
if($r->successful()) {
2023-06-21 11:22:20 +02:00
return $r->json()['client_token'];
2023-10-26 04:57:44 +02:00
}
2024-01-14 05:05:00 +01:00
2023-06-21 11:22:20 +02:00
throw new PaymentFailed('Unable to gain client token from Paypal. Check your configuration', 401);
}
2024-04-16 14:01:25 +02:00
private function getPaymentSource(): array
{
if($this->gateway_type_id == 1) {
return [
"card" => [
"attributes" => [
"verification" => [
"method" => "SCA_WHEN_REQUIRED", //SCA_ALWAYS
],
],
"name" => $this->client->present()->primary_contact_name(),
"email_address" => $this->client->present()->email(),
"address" => [
"address_line_1" => $this->client->address1,
"address_line_2" => $this->client->address2,
"admin_area_2" => $this->client->city,
"admin_area_1" => $this->client->state,
"postal_code" => $this->client->postal_code,
"country_code" => $this->client->country->iso_3166_2,
],
"experience_context" => [
"user_action" => "PAY_NOW"
],
"stored_credential" => [
"payment_initiator" => "MERCHANT", //"CUSTOMER" who initiated the transaction?
"payment_type" => "UNSCHEDULED",
"usage"=> "DERIVED",
],
],
];
}
return [
"paypal" => [
"name" => [
"given_name" => $this->client->present()->first_name(),
"surname" => $this->client->present()->last_name(),
],
"email_address" => $this->client->present()->email(),
"address" => [
"address_line_1" => $this->client->address1,
"address_line_2" => $this->client->address2,
"admin_area_2" => $this->client->city,
"admin_area_1" => $this->client->state,
"postal_code" => $this->client->postal_code,
"country_code" => $this->client->country->iso_3166_2,
],
"experience_context" => [
"user_action" => "PAY_NOW"
],
],
];
}
2023-06-21 11:22:20 +02:00
private function createOrder(array $data): string
{
$_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,
"payment_instruction" => [
"disbursement_mode" => "INSTANT",
],
$this->getShippingAddress(),
"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
2023-06-21 11:22:20 +02:00
$r = $this->gatewayRequest('/v2/checkout/orders', 'post', $order);
2023-06-20 07:51:29 +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
}
private function getShippingAddress(): ?array
{
return $this->company_gateway->require_shipping_address ?
[
"address" =>
[
"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(),
],
]
2024-02-13 05:25:18 +01:00
: null;
2023-06-21 11:22:20 +02:00
}
2023-06-19 06:25:42 +02:00
/**
* Generates the gateway request
*
* @param string $uri
* @param string $verb
* @param array $data
* @param ?array $headers
* @return \Illuminate\Http\Client\Response
*/
2023-06-21 11:22:20 +02:00
public function gatewayRequest(string $uri, string $verb, array $data, ?array $headers = [])
{
$this->init();
$r = Http::withToken($this->access_token)
2023-06-21 11:22:20 +02:00
->withHeaders($this->getHeaders($headers))
->{$verb}("{$this->api_endpoint_url}{$uri}", $data);
2023-10-26 04:57:44 +02:00
if($r->successful()) {
2023-06-21 11:22:20 +02:00
return $r;
2023-10-26 04:57:44 +02:00
}
2023-06-21 11:22:20 +02:00
SystemLogger::dispatch(
['response' => $r->body()],
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_FAILURE,
SystemLog::TYPE_PAYPAL,
$this->client,
2024-03-19 00:38:54 +01:00
$this->client->company ?? $this->company_gateway->company,
);
2023-06-21 11:22:20 +02:00
throw new PaymentFailed("Gateway failure - {$r->body()}", 401);
2023-06-19 06:25:42 +02:00
}
2023-06-21 11:22:20 +02:00
private function getHeaders(array $headers = []): array
{
return array_merge([
'Accept' => 'application/json',
'Content-type' => 'application/json',
'Accept-Language' => 'en_US',
], $headers);
}
2023-06-19 06:25:42 +02:00
private function feeCalc($invoice, $invoice_total)
{
$invoice->service()->removeUnpaidGatewayFees();
$invoice = $invoice->fresh();
$balance = floatval($invoice->balance);
$_updated_invoice = $invoice->service()->addGatewayFee($this->company_gateway, GatewayType::PAYPAL, $invoice_total)->save();
if (floatval($_updated_invoice->balance) > $balance) {
$fee = floatval($_updated_invoice->balance) - $balance;
$this->payment_hash->fee_total = $fee;
$this->payment_hash->save();
return $fee;
}
return 0;
}
2023-06-21 11:22:20 +02:00
2024-03-16 02:36:40 +01:00
public function auth(): bool
{
2023-10-26 04:57:44 +02:00
2024-03-16 02:36:40 +01:00
try {
$this->init()->getClientToken();
return true;
}
catch(\Exception $e) {
}
return false;
}
2024-03-19 00:38:54 +01:00
public function importCustomers()
{
return true;
}
2023-06-19 06:25:42 +02:00
}