This commit is contained in:
David Bomba 2023-10-16 12:05:19 +11:00
parent 0694378bb5
commit 0033fee578
14 changed files with 532 additions and 62 deletions

View File

@ -11,51 +11,52 @@
namespace App\Console\Commands;
use App\DataMapper\ClientRegistrationFields;
use App\DataMapper\CompanySettings;
use App\DataMapper\FeesAndLimits;
use App\Events\Invoice\InvoiceWasCreated;
use App\Events\RecurringInvoice\RecurringInvoiceWasCreated;
use App\Factory\GroupSettingFactory;
use App\Factory\InvoiceFactory;
use App\Factory\InvoiceItemFactory;
use App\Factory\RecurringInvoiceFactory;
use App\Factory\SubscriptionFactory;
use App\Helpers\Invoice\InvoiceSum;
use App\Jobs\Company\CreateCompanyTaskStatuses;
use App\Libraries\MultiDB;
use App\Models\Account;
use App\Models\BankIntegration;
use App\Models\BankTransaction;
use App\Models\BankTransactionRule;
use App\Models\Client;
use App\Models\ClientContact;
use App\Models\Company;
use App\Models\CompanyGateway;
use App\Models\CompanyToken;
use App\Models\Country;
use App\Models\Credit;
use App\Models\Expense;
use App\Models\Product;
use App\Models\Project;
use App\Models\Quote;
use App\Models\RecurringInvoice;
use App\Models\Task;
use App\Models\TaxRate;
use App\Models\User;
use App\Models\Vendor;
use App\Models\VendorContact;
use App\Repositories\InvoiceRepository;
use App\Utils\Ninja;
use App\Utils\Traits\GeneratesCounter;
use App\Utils\Traits\MakesHash;
use stdClass;
use Carbon\Carbon;
use Faker\Factory;
use App\Models\Task;
use App\Models\User;
use App\Utils\Ninja;
use App\Models\Quote;
use App\Models\Client;
use App\Models\Credit;
use App\Models\Vendor;
use App\Models\Account;
use App\Models\Company;
use App\Models\Country;
use App\Models\Expense;
use App\Models\Gateway;
use App\Models\Product;
use App\Models\Project;
use App\Models\TaxRate;
use App\Libraries\MultiDB;
use App\Models\CompanyToken;
use App\Models\ClientContact;
use App\Models\VendorContact;
use App\Models\CompanyGateway;
use App\Factory\InvoiceFactory;
use App\Models\BankIntegration;
use App\Models\BankTransaction;
use App\Utils\Traits\MakesHash;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use App\Models\RecurringInvoice;
use App\DataMapper\FeesAndLimits;
use App\DataMapper\CompanySettings;
use App\Factory\InvoiceItemFactory;
use App\Helpers\Invoice\InvoiceSum;
use App\Models\BankTransactionRule;
use App\Factory\GroupSettingFactory;
use App\Factory\SubscriptionFactory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Cache;
use App\Utils\Traits\GeneratesCounter;
use Illuminate\Support\Facades\Schema;
use stdClass;
use App\Repositories\InvoiceRepository;
use App\Factory\RecurringInvoiceFactory;
use App\Events\Invoice\InvoiceWasCreated;
use App\DataMapper\ClientRegistrationFields;
use App\Jobs\Company\CreateCompanyTaskStatuses;
use App\Events\RecurringInvoice\RecurringInvoiceWasCreated;
class CreateSingleAccount extends Command
{
@ -883,6 +884,28 @@ class CreateSingleAccount extends Command
$cg->fees_and_limits = $fees_and_limits;
$cg->save();
}
if (config('ninja.testvars.ppcp') && ($this->gateway == 'all' || $this->gateway == 'square')) {
$cg = new CompanyGateway;
$cg->company_id = $company->id;
$cg->user_id = $user->id;
$cg->gateway_key = '80af24a6a691230bbec33e930ab40666';
$cg->require_cvv = true;
$cg->require_billing_address = true;
$cg->require_shipping_address = true;
$cg->update_details = true;
$cg->config = encrypt(config('ninja.testvars.ppcp'));
$cg->save();
$fees_and_limits = new stdClass;
// $fees_and_limits->{$gateway_types[0]} = new FeesAndLimits;
$fees_and_limits->{3} = new FeesAndLimits;
$cg->fees_and_limits = $fees_and_limits;
$cg->save();
}
}
private function createRecurringInvoice($client)

View File

@ -194,21 +194,27 @@ class CompanyGatewayController extends BaseController
*/
public function store(StoreCompanyGatewayRequest $request)
{
$company_gateway = CompanyGatewayFactory::create(auth()->user()->company()->id, auth()->user()->id);
/** @var \App\Models\User $user */
$user = auth()->user();
$company_gateway = CompanyGatewayFactory::create($user->company()->id, $user->id);
$company_gateway->fill($request->all());
$company_gateway->save();
/*Always ensure at least one fees and limits object is set per gateway*/
if (! isset($company_gateway->fees_and_limits)) {
$gateway_types = $company_gateway->driver(new Client)->gatewayTypes();
$fees_and_limits = new \stdClass;
$fees_and_limits->{$gateway_types[0]} = new FeesAndLimits;
$company_gateway->fees_and_limits = $fees_and_limits;
$company_gateway->save();
/*Always ensure at least one fees and limits object is set per gateway*/
$gateway_types = $company_gateway->driver(new Client)->getAvailableMethods();
$fees_and_limits = $company_gateway->fees_and_limits;
foreach($gateway_types as $key => $gateway_type)
{
if(!property_exists($fees_and_limits, $key))
$fees_and_limits->{$key} = new FeesAndLimits;
}
$company_gateway->fees_and_limits = $fees_and_limits;
$company_gateway->save();
ApplePayDomain::dispatch($company_gateway, $company_gateway->company->db);
if (in_array($company_gateway->gateway_key, $this->stripe_keys)) {
@ -382,10 +388,18 @@ class CompanyGatewayController extends BaseController
{
$company_gateway->fill($request->all());
if (! $request->has('fees_and_limits')) {
$company_gateway->fees_and_limits = '';
/*Always ensure at least one fees and limits object is set per gateway*/
$gateway_types = $company_gateway->driver(new Client)->getAvailableMethods();
$fees_and_limits = $company_gateway->fees_and_limits;
foreach($gateway_types as $key => $gateway_type) {
if(!property_exists($fees_and_limits, $key)) {
$fees_and_limits->{$key} = new FeesAndLimits;
}
}
$company_gateway->fees_and_limits = $fees_and_limits;
$company_gateway->save();
if($company_gateway->gateway_key == $this->checkout_key) {

View File

@ -11,6 +11,7 @@
namespace App\Http\Requests\CompanyGateway;
use App\DataMapper\FeesAndLimits;
use App\Http\Requests\Request;
use App\Http\ValidationRules\ValidCompanyGatewayFeesAndLimitsRule;
use App\Models\Gateway;
@ -28,7 +29,10 @@ class StoreCompanyGatewayRequest extends Request
*/
public function authorize() : bool
{
return auth()->user()->isAdmin();
/** @var \App\Models\User $user */
$user = auth()->user();
return $user->isAdmin();
}
public function rules()
@ -64,6 +68,7 @@ class StoreCompanyGatewayRequest extends Request
if (isset($input['fees_and_limits'])) {
$input['fees_and_limits'] = $this->cleanFeesAndLimits($input['fees_and_limits']);
}
}
$this->replace($input);

View File

@ -27,7 +27,10 @@ class UpdateCompanyGatewayRequest extends Request
*/
public function authorize()
{
return auth()->user()->isAdmin();
/** @var \App\Models\User $user */
$user = auth()->user();
return $user->isAdmin();
}
public function rules()

View File

@ -117,7 +117,6 @@ class CompanyGateway extends BaseModel
16 => ['card' => 'images/credit_cards/Test-Discover-Icon.png', 'text' => 'Discover'],
];
// const TYPE_PAYPAL = 300;
// const TYPE_STRIPE = 301;
// const TYPE_LEDGER = 302;
@ -132,6 +131,7 @@ class CompanyGateway extends BaseModel
// const TYPE_MOLLIE = 312;
// const TYPE_EWAY = 313;
// const TYPE_FORTE = 314;
// const PAYPAL_PPCP = 323;
public $gateway_consts = [
'38f2c48af60c7dd69e04248cbb24c36e' => 300,
@ -150,6 +150,7 @@ class CompanyGateway extends BaseModel
'65faab2ab6e3223dbe848b1686490baz' => 320,
'b9886f9257f0c6ee7c302f1c74475f6c' => 321,
'hxd6gwg3ekb9tb3v9lptgx1mqyg69zu9' => 322,
'80af24a6a691230bbec33e930ab40666' => 323,
];
protected $touches = [];

View File

@ -90,7 +90,7 @@ class Gateway extends StaticModel
if ($this->id == 1) {
$link = 'http://reseller.authorize.net/application/?id=5560364';
} elseif ($this->id == 15) {
} elseif (in_array($this->id,[15,60,61])) {
$link = 'https://www.paypal.com/us/cgi-bin/webscr?cmd=_login-api-run';
} elseif ($this->id == 24) {
$link = 'https://www.2checkout.com/referral?r=2c37ac2298';
@ -202,7 +202,19 @@ class Gateway extends StaticModel
// GatewayType::PRZELEWY24 => ['refund' => false, 'token_billing' => false],
// GatewayType::SOFORT => ['refund' => false, 'token_billing' => false],
]; //Paypal
case 61:
return [
GatewayType::PAYPAL => ['refund' => false, 'token_billing' => false],
GatewayType::CREDIT_CARD => ['refund' => false, 'token_billing' => false],
GatewayType::VENMO => ['refund' => false, 'token_billing' => false],
// GatewayType::SEPA => ['refund' => false, 'token_billing' => false],
// GatewayType::BANCONTACT => ['refund' => false, 'token_billing' => false],
// GatewayType::EPS => ['refund' => false, 'token_billing' => false],
// GatewayType::MYBANK => ['refund' => false, 'token_billing' => false],
// GatewayType::PAYLATER => ['refund' => false, 'token_billing' => false],
// GatewayType::PRZELEWY24 => ['refund' => false, 'token_billing' => false],
// GatewayType::SOFORT => ['refund' => false, 'token_billing' => false],
]; //Paypal PPCP
default:
return [];
}

View File

@ -148,6 +148,8 @@ class SystemLog extends Model
const TYPE_RAZORPAY = 322;
const TYPE_PAYPAL_PPCP = 323;
const TYPE_QUOTA_EXCEEDED = 400;
const TYPE_UPSTREAM_FAILURE = 401;

View File

@ -109,6 +109,11 @@ class BaseDriver extends AbstractPaymentDriver
return $this;
}
public function getAvailableMethods(): array
{
return self::$methods;
}
/**
* Required fields for client to fill, to proceed with gateway actions.
*

View File

@ -0,0 +1,342 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2023. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\PaymentDrivers;
use App\Exceptions\PaymentFailed;
use App\Jobs\Util\SystemLogger;
use App\Models\GatewayType;
use App\Models\Invoice;
use App\Models\PaymentType;
use App\Models\SystemLog;
use App\Utils\Traits\MakesHash;
use Carbon\Carbon;
use Illuminate\Support\Facades\Http;
use Omnipay\Omnipay;
class PayPalPPCPPaymentDriver extends BaseDriver
{
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_PPCP;
private string $api_endpoint_url = '';
private string $paypal_payment_method = '';
protected ?string $access_token = null;
protected ?Carbon $token_expiry = null;
private array $funding_options = [
3 => 'paypal',
1 => 'card',
25 => 'venmo',
// 9 => 'sepa',
// 12 => 'bancontact',
// 17 => 'eps',
// 15 => 'giropay',
// 13 => 'ideal',
// 26 => 'mercadopago',
// 27 => 'mybank',
// 28 => 'paylater',
// 16 => 'p24',
// 7 => 'sofort'
];
public function gatewayTypes(): array
{
$funding_options = [];
foreach ($this->company_gateway->fees_and_limits as $key => $value) {
if ($value->is_enabled) {
$funding_options[] = $key;
}
}
return $funding_options;
}
/**
* Initialize the Paypal gateway.
*
* Attempt to generate and return the access token.
*
* @return self
*/
public function init(): self
{
$this->api_endpoint_url = $this->company_gateway->getConfigField('testMode') ? 'https://api-m.sandbox.paypal.com' : 'https://api-m.paypal.com';
$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);
}
return $this;
}
public function setPaymentMethod($payment_method_id)
{
if(!$payment_method_id) {
return $this;
}
$this->paypal_payment_method = $this->funding_options[$payment_method_id];
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)
{
$this->init();
$data['gateway'] = $this;
$this->payment_hash->data = array_merge((array) $this->payment_hash->data, ['amount' => $data['total']['amount_with_fee']]);
$this->payment_hash->save();
$data['client_id'] = $this->company_gateway->getConfigField('clientId');
$data['token'] = $this->access_token;
$data['order_id'] = $this->createOrder($data);
$data['funding_options'] = $this->paypal_payment_method;
return render('gateways.paypal.pay', $data);
}
private function getFundingOptions():string
{
$enums = [
3 => 'paypal',
1 => 'card',
25 => 'venmo',
// 9 => 'sepa',
// 12 => 'bancontact',
// 17 => 'eps',
// 15 => 'giropay',
// 13 => 'ideal',
// 26 => 'mercadopago',
// 27 => 'mybank',
// 28 => 'paylater',
// 16 => 'p24',
// 7 => 'sofort'
];
$funding_options = '';
foreach($this->company_gateway->fees_and_limits as $key => $value) {
if($value->is_enabled) {
$funding_options .=$enums[$key].',';
}
}
return rtrim($funding_options, ',');
}
public function processPaymentResponse($request)
{
// $response = json_decode($request['gateway_response'], true);
// if($response['status'] == 'COMPLETED' && isset($response['purchase_units'])) {
// $data = [
// 'payment_type' => PaymentType::PAYPAL,
// 'amount' => $response['purchase_units'][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);
// 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)]);
// } else {
// SystemLogger::dispatch(
// ['response' => $response],
// SystemLog::CATEGORY_GATEWAY_RESPONSE,
// SystemLog::EVENT_GATEWAY_FAILURE,
// SystemLog::TYPE_PAYPAL,
// $this->client,
// $this->client->company,
// );
// throw new PaymentFailed('Payment failed. Please try again.', 401);
// }
}
private function createOrder(array $data): string
{
$_invoice = collect($this->payment_hash->data->invoices)->first();
$invoice = Invoice::withTrashed()->find($this->decodePrimaryKey($_invoice->invoice_id));
$order = [
"intent" => "CAPTURE",
"payer" => [
"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_1" => $this->client->city,
"admin_area_2" => $this->client->state,
"postal_code" => $this->client->postal_code,
"country_code" => $this->client->country->iso_3166_2,
]
],
"purchase_units" => [
[
"description" =>ctrans('texts.invoice_number').'# '.$invoice->number,
"invoice_id" => $invoice->number,
"amount" => [
"value" => (string)$data['amount_with_fee'],
"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,
"quantity" => "1",
"unit_amount" => [
"currency_code" => $this->client->currency()->code,
"value" => (string)$data['amount_with_fee']
],
],
],
]
]
];
$r = $this->gatewayRequest('/v2/checkout/orders', 'post', $order);
return $r->json()['id'];
}
public function gatewayRequest(string $uri, string $verb, array $data, ?array $headers = [])
{
$this->init();
$r = Http::withToken($this->access_token)
->withHeaders($this->getHeaders($headers))
->{$verb}("{$this->api_endpoint_url}{$uri}", $data);
if($r->successful()) {
return $r;
}
throw new PaymentFailed("Gateway failure - {$r->body()}", 401);
}
private function getHeaders(array $headers = []): array
{
return array_merge([
'Accept' => 'application/json',
'Content-type' => 'application/json',
'Accept-Language' => 'en_US',
'PayPal-Partner-Attribution-Id' => 'invoiceninja_SP_PPCP'
], $headers);
}
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;
// }
}
}

View File

@ -139,13 +139,13 @@ class StripePaymentDriver extends BaseDriver
return $this;
}
/**
* Returns the gateway types.
*/
public function gatewayTypes(): array
{
$types = [
// GatewayType::CRYPTO,
GatewayType::CREDIT_CARD,
];

View File

@ -84,6 +84,7 @@ return [
'password' => 'password',
'stripe' => env('STRIPE_KEYS', ''),
'paypal' => env('PAYPAL_KEYS', ''),
'ppcp' => env('PPCP_KEYS', ''),
'paypal_rest' => env('PAYPAL_REST_KEYS', ''),
'authorize' => env('AUTHORIZE_KEYS', ''),
'checkout' => env('CHECKOUT_KEYS', ''),
@ -221,4 +222,8 @@ return [
'client_id' => env('SHOPIFY_CLIENT_ID', null),
'client_secret' => env('SHOPIFY_CLIENT_SECRET', null),
],
'paypal' => [
'secret' => env('PAYPAL_SECRET', null),
'client_id' => env('PAYPAL_CLIENT_ID', null),
]
];

View File

@ -0,0 +1,49 @@
<?php
use App\Utils\Ninja;
use App\Models\Gateway;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
if(!Gateway::find(61))
{
$fields = new \stdClass;
$fields->clientId = "";
$fields->secret = "";
$fields->testMode = false;
$paypal = new Gateway;
$paypal->id = 61;
$paypal->name = 'PayPal Platform';
$paypal->key = '80af24a6a691230bbec33e930ab40666';
$paypal->provider = 'PayPal_PPCP';
$paypal->is_offsite = false;
$paypal->fields = \json_encode($fields);
$paypal->visible = 1;
$paypal->site_url = 'https://www.paypal.com/';
$paypal->save();
}
Gateway::whereIn('id', [60, 15])->update(['visible' => 0]);
}
/**
* Reverse the migrations.
*/
public function down(): void
{
//
}
};

View File

@ -84,6 +84,7 @@ class PaymentLibrariesSeeder extends Seeder
['id' => 58, 'name' => 'Razorpay', 'provider' => 'Razorpay', 'is_offsite' => false, 'sort_order' => 21, 'key' => 'hxd6gwg3ekb9tb3v9lptgx1mqyg69zu9', 'fields' => '{"apiKey":"","apiSecret":""}'],
['id' => 59, 'name' => 'Forte', 'provider' => 'Forte', 'is_offsite' => false, 'sort_order' => 21, 'key' => 'kivcvjexxvdiyqtj3mju5d6yhpeht2xs', 'fields' => '{"testMode":false,"apiLoginId":"","apiAccessId":"","secureKey":"","authOrganizationId":"","organizationId":"","locationId":""}'],
['id' => 60, 'name' => 'PayPal REST', 'provider' => 'PayPal_Rest', 'key' => '80af24a6a691230bbec33e930ab40665', 'fields' => '{"clientId":"","secret":"","signature":"","testMode":false}'],
['id' => 61, 'name' => 'PayPal Platform', 'provider' => 'PayPal_PPCP', 'key' => '80af24a6a691230bbec33e930ab40666', 'fields' => '{"clientId":"","secret":"","signature":"","testMode":false}'],
];
foreach ($gateways as $gateway) {
@ -100,12 +101,11 @@ class PaymentLibrariesSeeder extends Seeder
Gateway::query()->update(['visible' => 0]);
Gateway::whereIn('id', [1,3,7,11,15,20,39,46,55,50,57,52,58,59,60])->update(['visible' => 1]);
Gateway::whereIn('id', [1,3,7,11,15,20,39,46,55,50,57,52,58,59,60,61])->update(['visible' => 1]);
if (Ninja::isHosted()) {
Gateway::whereIn('id', [20])->update(['visible' => 0]);
Gateway::whereIn('id', [56])->update(['visible' => 1]);
Gateway::whereIn('id', [49])->update(['visible' => 1]);
Gateway::whereIn('id', [20,49])->update(['visible' => 0]);
Gateway::whereIn('id', [56,61])->update(['visible' => 1]);
}
Gateway::all()->each(function ($gateway) {

File diff suppressed because one or more lines are too long