Merge pull request #9203 from turbo124/v5-develop

Allow Gocardless ACSS payments for CAD customers
This commit is contained in:
David Bomba 2024-01-28 10:47:26 +11:00 committed by GitHub
commit 97e7f55bc0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
25 changed files with 394 additions and 159 deletions

View File

@ -154,6 +154,7 @@ class NinjaPlanController extends Controller
$account->is_trial = true; $account->is_trial = true;
$account->hosted_company_count = 10; $account->hosted_company_count = 10;
$account->trial_started = now(); $account->trial_started = now();
$account->trial_plan = 'pro';
$account->save(); $account->save();
} }

View File

@ -27,7 +27,7 @@ class CreatePaymentMethodRequest extends FormRequest
->filter(function ($method) use (&$available_methods) { ->filter(function ($method) use (&$available_methods) {
$available_methods[] = $method['gateway_type_id']; $available_methods[] = $method['gateway_type_id'];
}); });
if (in_array($this->query('method'), $available_methods)) { if (in_array($this->query('method'), $available_methods)) {
return true; return true;
} }

View File

@ -259,15 +259,23 @@ class NinjaMailerJob implements ShouldQueue
$t = app('translator'); $t = app('translator');
$t->replace(Ninja::transformTranslations($this->nmo->settings)); $t->replace(Ninja::transformTranslations($this->nmo->settings));
/** Force free/trials onto specific mail driver */
if(Ninja::isHosted() && !$this->company->account->isPaid())
{
$this->mailer = 'mailgun';
$this->setHostedMailgunMailer();
return $this;
}
switch ($this->nmo->settings->email_sending_method) { switch ($this->nmo->settings->email_sending_method) {
case 'default': case 'default':
$this->mailer = config('mail.default'); $this->mailer = config('mail.default');
// $this->setHostedMailgunMailer(); //should only be activated if hosted platform needs to fall back to mailgun // $this->setHostedMailgunMailer(); //should only be activated if hosted platform needs to fall back to mailgun
break; return $this;
case 'mailgun': case 'mailgun':
$this->mailer = 'mailgun'; $this->mailer = 'mailgun';
$this->setHostedMailgunMailer(); $this->setHostedMailgunMailer();
break; return $this;
case 'gmail': case 'gmail':
$this->mailer = 'gmail'; $this->mailer = 'gmail';
$this->setGmailMailer(); $this->setGmailMailer();

View File

@ -59,7 +59,7 @@ class CleanStaleInvoiceOrder implements ShouldQueue
Invoice::query() Invoice::query()
->withTrashed() ->withTrashed()
->where('status_id', Invoice::STATUS_SENT) ->where('status_id', Invoice::STATUS_SENT)
->whereBetween('created_at', [now()->subHours(1), now()->subMinutes(10)]) ->whereBetween('created_at', [now()->subHours(1), now()->subMinutes(30)])
->where('balance', '>', 0) ->where('balance', '>', 0)
->cursor() ->cursor()
->each(function ($invoice) { ->each(function ($invoice) {

View File

@ -353,6 +353,7 @@ class BillingPortalPurchase extends Component
$this->payment_method_id = $gateway_type_id; $this->payment_method_id = $gateway_type_id;
$this->handleBeforePaymentEvents(); $this->handleBeforePaymentEvents();
} }
/** /**

View File

@ -363,9 +363,10 @@ class Account extends BaseModel
return false; return false;
} }
$plan_details = $this->getPlanDetails(); //@27-01-2024 - updates for logic around trials
return !$this->plan_paid && $this->trial_started && Carbon::parse($this->trial_started)->addDays(14)->gte(now()->subHours(12));
return $plan_details && $plan_details['trial']; // $plan_details = $this->getPlanDetails();
// return $plan_details && $plan_details['trial'];
} }
public function startTrial($plan): void public function startTrial($plan): void

View File

@ -688,6 +688,11 @@ class Client extends BaseModel implements HasLocalePreference
return GatewayType::SEPA; return GatewayType::SEPA;
} }
//Special handler for GoCardless
if($this->currency()->code == 'CAD' && ($this->getBankTransferGateway()->gateway_key == 'b9886f9257f0c6ee7c302f1c74475f6c') ?? false) {
return GatewayType::DIRECT_DEBIT;
}
if (in_array($this->currency()->code, ['EUR', 'GBP','DKK','SEK','AUD','NZD','USD'])) { if (in_array($this->currency()->code, ['EUR', 'GBP','DKK','SEK','AUD','NZD','USD'])) {
return GatewayType::DIRECT_DEBIT; return GatewayType::DIRECT_DEBIT;
} }

View File

@ -148,7 +148,7 @@ class CompanyGateway extends BaseModel
'944c20175bbe6b9972c05bcfe294c2c7' => 313, '944c20175bbe6b9972c05bcfe294c2c7' => 313,
'kivcvjexxvdiyqtj3mju5d6yhpeht2xs' => 314, 'kivcvjexxvdiyqtj3mju5d6yhpeht2xs' => 314,
'65faab2ab6e3223dbe848b1686490baz' => 320, '65faab2ab6e3223dbe848b1686490baz' => 320,
'b9886f9257f0c6ee7c302f1c74475f6c' => 321, 'b9886f9257f0c6ee7c302f1c74475f6c' => 321, //GoCardless
'hxd6gwg3ekb9tb3v9lptgx1mqyg69zu9' => 322, 'hxd6gwg3ekb9tb3v9lptgx1mqyg69zu9' => 322,
'80af24a6a691230bbec33e930ab40666' => 323, '80af24a6a691230bbec33e930ab40666' => 323,
]; ];

View File

@ -314,9 +314,9 @@ class Payment extends BaseModel
return $this->createClientDate($this->date, $this->client->timezone()->name)->format($date_format->format); return $this->createClientDate($this->date, $this->client->timezone()->name)->format($date_format->format);
} }
public static function badgeForStatus(int $status): string public function badgeForStatus(): string
{ {
switch ($status) { switch ($this->status_id) {
case self::STATUS_PENDING: case self::STATUS_PENDING:
return '<h6><span class="badge badge-secondary">'.ctrans('texts.payment_status_1').'</span></h6>'; return '<h6><span class="badge badge-secondary">'.ctrans('texts.payment_status_1').'</span></h6>';
case self::STATUS_CANCELLED: case self::STATUS_CANCELLED:
@ -324,6 +324,10 @@ class Payment extends BaseModel
case self::STATUS_FAILED: case self::STATUS_FAILED:
return '<h6><span class="badge badge-danger">'.ctrans('texts.payment_status_3').'</span></h6>'; return '<h6><span class="badge badge-danger">'.ctrans('texts.payment_status_3').'</span></h6>';
case self::STATUS_COMPLETED: case self::STATUS_COMPLETED:
if($this->amount > $this->applied)
return '<h6><span class="badge badge-info">' . ctrans('texts.partially_unapplied') . '</span></h6>';
return '<h6><span class="badge badge-info">'.ctrans('texts.payment_status_4').'</span></h6>'; return '<h6><span class="badge badge-info">'.ctrans('texts.payment_status_4').'</span></h6>';
case self::STATUS_PARTIALLY_REFUNDED: case self::STATUS_PARTIALLY_REFUNDED:
return '<h6><span class="badge badge-success">'.ctrans('texts.payment_status_5').'</span></h6>'; return '<h6><span class="badge badge-success">'.ctrans('texts.payment_status_5').'</span></h6>';

View File

@ -173,10 +173,6 @@ class CreditCard implements MethodInterface
if ($request->has('token') && ! is_null($request->token) && ! empty($request->token)) { if ($request->has('token') && ! is_null($request->token) && ! empty($request->token)) {
return $this->attemptPaymentUsingToken($request); return $this->attemptPaymentUsingToken($request);
} }
if($this->checkout->company_gateway->update_details) {
$this->checkout->updateCustomer();
}
return $this->attemptPaymentUsingCreditCard($request); return $this->attemptPaymentUsingCreditCard($request);
} }
@ -235,8 +231,13 @@ class CreditCard implements MethodInterface
try { try {
$response = $this->checkout->gateway->getPaymentsClient()->requestPayment($paymentRequest); $response = $this->checkout->gateway->getPaymentsClient()->requestPayment($paymentRequest);
if($this->checkout->company_gateway->update_details && isset($response['customer'])) {
$this->checkout->updateCustomer($response['customer']['id'] ?? '');
}
if ($response['status'] == 'Authorized') { if ($response['status'] == 'Authorized') {
return $this->processSuccessfulPayment($response); return $this->processSuccessfulPayment($response);
} }

View File

@ -44,9 +44,6 @@ use Checkout\Payments\Request\Source\RequestIdSource;
use Exception; use Exception;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
//use Checkout\Customers\Four\CustomerRequest as FourCustomerRequest;
//use Checkout\Payments\Four\Request\Source\RequestIdSource as SourceRequestIdSource;
class CheckoutComPaymentDriver extends BaseDriver class CheckoutComPaymentDriver extends BaseDriver
{ {
use SystemLogTrait; use SystemLogTrait;
@ -332,10 +329,14 @@ class CheckoutComPaymentDriver extends BaseDriver
} }
} }
public function updateCustomer() public function updateCustomer($customer_id = null)
{ {
if(!$customer_id)
return;
try { try {
$request = new CustomerRequest(); $request = new CustomerRequest();
$phone = new Phone(); $phone = new Phone();
@ -344,11 +345,13 @@ class CheckoutComPaymentDriver extends BaseDriver
$request->name = $this->client->present()->name(); $request->name = $this->client->present()->name();
$request->phone = $phone; $request->phone = $phone;
$response = $this->gateway->getCustomersClient()->update("customer_id", $request); $response = $this->gateway->getCustomersClient()->update($customer_id, $request);
} catch (CheckoutApiException $e) { } catch (CheckoutApiException $e) {
nlog($e->getMessage());
} catch (CheckoutAuthorizationException $e) { } catch (CheckoutAuthorizationException $e) {
nlog($e->getMessage());
} }
} }
@ -385,10 +388,6 @@ class CheckoutComPaymentDriver extends BaseDriver
$this->init(); $this->init();
if($this->company_gateway->update_details) {
$this->updateCustomer();
}
$paymentRequest = $this->bootTokenRequest($cgt->token); $paymentRequest = $this->bootTokenRequest($cgt->token);
$paymentRequest->amount = $this->convertToCheckoutAmount($amount, $this->client->getCurrencyCode()); $paymentRequest->amount = $this->convertToCheckoutAmount($amount, $this->client->getCurrencyCode());
$paymentRequest->reference = '#'.$invoice->number.' - '.now(); $paymentRequest->reference = '#'.$invoice->number.' - '.now();

View File

@ -11,23 +11,23 @@
namespace App\PaymentDrivers; namespace App\PaymentDrivers;
use App\Factory\ClientContactFactory;
use App\Factory\ClientFactory;
use App\Http\Requests\Payments\PaymentWebhookRequest;
use App\Jobs\Mail\PaymentFailedMailer;
use App\Jobs\Util\SystemLogger;
use App\Models\Client; use App\Models\Client;
use App\Models\ClientGatewayToken;
use App\Models\Country; use App\Models\Country;
use App\Models\GatewayType;
use App\Models\Invoice; use App\Models\Invoice;
use App\Models\Payment; use App\Models\Payment;
use App\Models\SystemLog;
use App\Models\GatewayType;
use App\Models\PaymentHash; use App\Models\PaymentHash;
use App\Models\PaymentType; use App\Models\PaymentType;
use App\Models\SystemLog; use App\Factory\ClientFactory;
use App\Utils\Traits\GeneratesCounter; use App\Jobs\Util\SystemLogger;
use App\Utils\Traits\MakesHash; use App\Utils\Traits\MakesHash;
use App\Models\ClientGatewayToken;
use App\Factory\ClientContactFactory;
use App\Jobs\Mail\PaymentFailedMailer;
use App\Utils\Traits\GeneratesCounter;
use Illuminate\Database\QueryException; use Illuminate\Database\QueryException;
use App\Http\Requests\Payments\PaymentWebhookRequest;
class GoCardlessPaymentDriver extends BaseDriver class GoCardlessPaymentDriver extends BaseDriver
{ {
@ -79,8 +79,7 @@ class GoCardlessPaymentDriver extends BaseDriver
if ( if (
$this->client $this->client
&& isset($this->client->country) && isset($this->client->country)
// && in_array($this->client->country->iso_3166_3, ['GBR']) && in_array($this->client->currency()->code, ['EUR', 'GBP','DKK','SEK','AUD','NZD','CAD'])
&& in_array($this->client->currency()->code, ['EUR', 'GBP','DKK','SEK','AUD','NZD'])
) { ) {
$types[] = GatewayType::DIRECT_DEBIT; $types[] = GatewayType::DIRECT_DEBIT;
} }
@ -92,7 +91,7 @@ class GoCardlessPaymentDriver extends BaseDriver
if ($this->client->currency()->code === 'GBP') { if ($this->client->currency()->code === 'GBP') {
$types[] = GatewayType::INSTANT_BANK_PAY; $types[] = GatewayType::INSTANT_BANK_PAY;
} }
return $types; return $types;
} }

View File

@ -445,7 +445,7 @@ class PayPalPPCPPaymentDriver extends BaseDriver
"items" => [ "items" => [
[ [
"name" => ctrans('texts.invoice_number').'# '.$invoice->number, "name" => ctrans('texts.invoice_number').'# '.$invoice->number,
"description" => substr($description, 0, 127), "description" => mb_substr($description, 0, 127),
"quantity" => "1", "quantity" => "1",
"unit_amount" => [ "unit_amount" => [
"currency_code" => $this->client->currency()->code, "currency_code" => $this->client->currency()->code,
@ -519,9 +519,6 @@ class PayPalPPCPPaymentDriver extends BaseDriver
->withHeaders($this->getHeaders($headers)) ->withHeaders($this->getHeaders($headers))
->{$verb}("{$this->api_endpoint_url}{$uri}", $data); ->{$verb}("{$this->api_endpoint_url}{$uri}", $data);
// nlog($r);
// nlog($r->json());
if($r->successful()) { if($r->successful()) {
return $r; return $r;
} }

View File

@ -12,15 +12,16 @@
namespace App\PaymentDrivers; namespace App\PaymentDrivers;
use App\Exceptions\PaymentFailed; use Carbon\Carbon;
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 Illuminate\Support\Facades\Http;
use Omnipay\Omnipay; use Omnipay\Omnipay;
use App\Models\Invoice;
use App\Models\SystemLog;
use App\Models\GatewayType;
use App\Models\PaymentType;
use App\Jobs\Util\SystemLogger;
use App\Utils\Traits\MakesHash;
use App\Exceptions\PaymentFailed;
use Illuminate\Support\Facades\Http;
class PayPalRestPaymentDriver extends BaseDriver class PayPalRestPaymentDriver extends BaseDriver
{ {
@ -40,6 +41,12 @@ class PayPalRestPaymentDriver extends BaseDriver
private string $paypal_payment_method = ''; private string $paypal_payment_method = '';
private ?int $gateway_type_id = null;
protected mixed $access_token = null;
protected ?Carbon $token_expiry = null;
private array $funding_options = [ private array $funding_options = [
3 => 'paypal', 3 => 'paypal',
1 => 'card', 1 => 'card',
@ -51,7 +58,7 @@ class PayPalRestPaymentDriver extends BaseDriver
// 13 => 'ideal', // 13 => 'ideal',
// 26 => 'mercadopago', // 26 => 'mercadopago',
// 27 => 'mybank', // 27 => 'mybank',
// 28 => 'paylater', 28 => 'paylater',
// 16 => 'p24', // 16 => 'p24',
// 7 => 'sofort' // 7 => 'sofort'
]; ];
@ -74,25 +81,61 @@ class PayPalRestPaymentDriver extends BaseDriver
public function init() public function init()
{ {
$this->omnipay_gateway = Omnipay::create( // $this->omnipay_gateway = Omnipay::create(
$this->company_gateway->gateway->provider // $this->company_gateway->gateway->provider
); // );
$this->omnipay_gateway->initialize((array) $this->company_gateway->getConfig());
// $this->omnipay_gateway->initialize((array) $this->company_gateway->getConfig());
$this->api_endpoint_url = $this->company_gateway->getConfigField('testMode') ? 'https://api-m.sandbox.paypal.com' : 'https://api-m.paypal.com'; $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; return $this;
} }
public function setPaymentMethod($payment_method_id) 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;
}
public function setPaymentMethod($payment_method_id): self
{ {
if(!$payment_method_id) { if(!$payment_method_id) {
return $this; return $this;
} }
$this->gateway_type_id = $payment_method_id;
$this->paypal_payment_method = $this->funding_options[$payment_method_id]; $this->paypal_payment_method = $this->funding_options[$payment_method_id];
return $this; return $this;
} }
@ -122,7 +165,9 @@ class PayPalRestPaymentDriver extends BaseDriver
$data['client_id'] = $this->company_gateway->getConfigField('clientId'); $data['client_id'] = $this->company_gateway->getConfigField('clientId');
$data['token'] = $this->getClientToken(); $data['token'] = $this->getClientToken();
$data['order_id'] = $this->createOrder($data); $data['order_id'] = $this->createOrder($data);
$data['funding_options'] = $this->paypal_payment_method; $data['funding_source'] = $this->paypal_payment_method;
$data['gateway_type_id'] = $this->gateway_type_id;
$data['currency'] = $this->client->currency()->code;
return render('gateways.paypal.pay', $data); return render('gateways.paypal.pay', $data);
@ -166,13 +211,43 @@ class PayPalRestPaymentDriver extends BaseDriver
public function processPaymentResponse($request) public function processPaymentResponse($request)
{ {
$this->init();
$request['gateway_response'] = str_replace("Error: ", "", $request['gateway_response']);
$response = json_decode($request['gateway_response'], true); $response = json_decode($request['gateway_response'], true);
if($response['status'] == 'COMPLETED' && isset($response['purchase_units'])) { //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);
}
$r = $this->gatewayRequest("/v2/checkout/orders/{$orderID}/capture", 'post', ['body' => '']);
$response = $r;
if(isset($response['status']) && $response['status'] == 'COMPLETED' && isset($response['purchase_units'])) {
$data = [ $data = [
'payment_type' => PaymentType::PAYPAL, 'payment_type' => $this->getPaymentMethod($request->gateway_type_id),
'amount' => $response['purchase_units'][0]['amount']['value'], 'amount' => $response['purchase_units'][0]['payments']['captures'][0]['amount']['value'],
'transaction_reference' => $response['purchase_units'][0]['payments']['captures'][0]['id'], 'transaction_reference' => $response['purchase_units'][0]['payments']['captures'][0]['id'],
'gateway_type_id' => GatewayType::PAYPAL, 'gateway_type_id' => GatewayType::PAYPAL,
]; ];
@ -192,6 +267,10 @@ class PayPalRestPaymentDriver extends BaseDriver
} else { } else {
if(isset($response['headers']) ?? false) {
unset($response['headers']);
}
SystemLogger::dispatch( SystemLogger::dispatch(
['response' => $response], ['response' => $response],
SystemLog::CATEGORY_GATEWAY_RESPONSE, SystemLog::CATEGORY_GATEWAY_RESPONSE,
@ -201,9 +280,11 @@ class PayPalRestPaymentDriver extends BaseDriver
$this->client->company, $this->client->company,
); );
$message = $response['body']['details'][0]['description'] ?? 'Payment failed. Please try again.';
throw new PaymentFailed('Payment failed. Please try again.', 401); throw new PaymentFailed($message, 400);
} }
} }
private function getClientToken(): string private function getClientToken(): string
@ -226,60 +307,169 @@ class PayPalRestPaymentDriver extends BaseDriver
$invoice = Invoice::withTrashed()->find($this->decodePrimaryKey($_invoice->invoice_id)); $invoice = Invoice::withTrashed()->find($this->decodePrimaryKey($_invoice->invoice_id));
$description = collect($invoice->line_items)->map(function ($item) {
return $item->notes;
})->implode("\n");
$order = [ $order = [
"intent" => "CAPTURE",
"payer" => [ "intent" => "CAPTURE",
"name" => [ "payment_source" => [
"given_name" => $this->client->present()->first_name(), "paypal" => [
"surname" => $this->client->present()->last_name(),
], "name" => [
"email_address" => $this->client->present()->email(), "given_name" => $this->client->present()->first_name(),
"address" => [ "surname" => $this->client->present()->last_name(),
"address_line_1" => $this->client->address1, ],
"address_line_2" => $this->client->address2, "email_address" => $this->client->present()->email(),
"admin_area_1" => $this->client->city, "address" => [
"admin_area_2" => $this->client->state, "address_line_1" => $this->client->address1,
"postal_code" => $this->client->postal_code, "address_line_2" => $this->client->address2,
"country_code" => $this->client->country->iso_3166_2, "admin_area_2" => $this->client->city,
] "admin_area_1" => $this->client->state,
], "postal_code" => $this->client->postal_code,
"purchase_units" => [ "country_code" => $this->client->country->iso_3166_2,
[ ],
"description" => ctrans('texts.invoice_number').'# '.$invoice->number, "experience_context" => [
"invoice_id" => $invoice->number, "user_action" => "PAY_NOW"
"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']
], ],
], ],
], "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'],
"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']
],
],
],
],
]
];
if($shipping = $this->getShippingAddress()) {
$order['purchase_units'][0]["shipping"] = $shipping;
}
$r = $this->gatewayRequest('/v2/checkout/orders', 'post', $order); $r = $this->gatewayRequest('/v2/checkout/orders', 'post', $order);
// nlog($r->json());
return $r->json()['id']; return $r->json()['id'];
// $_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'];
} }
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(),
],
]
: null;
}
/**
* Generates the gateway request
*
* @param string $uri
* @param string $verb
* @param array $data
* @param ?array $headers
* @return \Illuminate\Http\Client\Response
*/
public function gatewayRequest(string $uri, string $verb, array $data, ?array $headers = []) public function gatewayRequest(string $uri, string $verb, array $data, ?array $headers = [])
{ {
$r = Http::withToken($this->omnipay_gateway->getToken()) $this->init();
$r = Http::withToken($this->access_token)
->withHeaders($this->getHeaders($headers)) ->withHeaders($this->getHeaders($headers))
->{$verb}("{$this->api_endpoint_url}{$uri}", $data); ->{$verb}("{$this->api_endpoint_url}{$uri}", $data);
@ -287,6 +477,15 @@ class PayPalRestPaymentDriver extends BaseDriver
return $r; return $r;
} }
SystemLogger::dispatch(
['response' => $r->body()],
SystemLog::CATEGORY_GATEWAY_RESPONSE,
SystemLog::EVENT_GATEWAY_FAILURE,
SystemLog::TYPE_PAYPAL,
$this->client,
$this->client->company,
);
throw new PaymentFailed("Gateway failure - {$r->body()}", 401); throw new PaymentFailed("Gateway failure - {$r->body()}", 401);
} }

View File

@ -44,6 +44,7 @@ class InstantPayment
public function run() public function run()
{ {
nlog($this->request->all());
$is_credit_payment = false; $is_credit_payment = false;
$tokens = []; $tokens = [];

View File

@ -484,6 +484,14 @@ class Email implements ShouldQueue
*/ */
private function setMailDriver(): self private function setMailDriver(): self
{ {
/** Force free/trials onto specific mail driver */
if(Ninja::isHosted() && !$this->company->account->isPaid()) {
$this->mailer = 'mailgun';
$this->setHostedMailgunMailer();
return $this;
}
switch ($this->email_object->settings->email_sending_method) { switch ($this->email_object->settings->email_sending_method) {
case 'default': case 'default':
$this->mailer = config('mail.default'); $this->mailer = config('mail.default');

View File

@ -651,7 +651,7 @@ class TemplateService
return [ return [
'status' => $payment->stringStatus($payment->status_id), 'status' => $payment->stringStatus($payment->status_id),
'badge' => $payment->badgeForStatus($payment->status_id), 'badge' => $payment->badgeForStatus(),
'amount' => Number::formatMoney($payment->amount, $payment->client), 'amount' => Number::formatMoney($payment->amount, $payment->client),
'applied' => Number::formatMoney($payment->applied, $payment->client), 'applied' => Number::formatMoney($payment->applied, $payment->client),
'balance' => Number::formatMoney(($payment->amount - $payment->refunded - $payment->applied), $payment->client), 'balance' => Number::formatMoney(($payment->amount - $payment->refunded - $payment->applied), $payment->client),

View File

@ -6,18 +6,19 @@
@stop @stop
@push('footer') @push('footer')
<script> <script>
function updateGatewayFields(companyGatewayId, paymentMethodId) {
document.getElementById('company_gateway_id').value = companyGatewayId;
document.getElementById('payment_method_id').value = paymentMethodId;
}
document.addEventListener('livewire:init', () => {
document.addEventListener('livewire:init', () => { Livewire.on('beforePaymentEventsCompleted', () => {
setTimeout(() => {
document.getElementById('payment-method-form').submit()
}, 2000);
});
Livewire.on('beforePaymentEventsCompleted', () => document.getElementById('payment-method-form').submit()); });
});
</script> </script>
@endpush @endpush

View File

@ -7,14 +7,8 @@
@push('footer') @push('footer')
<script> <script>
function updateGatewayFields(companyGatewayId, paymentMethodId) {
console.log(companyGatewayId, paymentMethodId);
document.getElementById('company_gateway_id').value = companyGatewayId;
document.getElementById('payment_method_id').value = paymentMethodId;
}
document.addEventListener('livewire:init', () => { document.addEventListener('livewire:init', () => {
Livewire.on('beforePaymentEventsCompleted', () => { Livewire.on('beforePaymentEventsCompleted', () => {
setTimeout(() => { setTimeout(() => {

View File

@ -143,7 +143,7 @@
@if($steps['started_payment'] == false) @if($steps['started_payment'] == false)
@foreach($this->methods as $method) @foreach($this->methods as $method)
<button <button
wire:click="handleMethodSelectingEvent('{{ $method['company_gateway_id'] }}', '{{ $method['gateway_type_id'] }}')" wire:click="handleMethodSelectingEvent('{{ $method['company_gateway_id'] }}', '{{ $method['gateway_type_id'] }}'); $wire.$refresh(); "
class="px-3 py-2 border rounded mr-4 hover:border-blue-600"> class="px-3 py-2 border rounded mr-4 hover:border-blue-600">
{{ $method['label'] }} {{ $method['label'] }}
</button> </button>

View File

@ -66,7 +66,7 @@
{{ \Illuminate\Support\Str::limit($payment->transaction_reference, 35) }} {{ \Illuminate\Support\Str::limit($payment->transaction_reference, 35) }}
</td> </td>
<td class="px-6 py-4 whitespace-nowrap text-sm leading-5 text-gray-500"> <td class="px-6 py-4 whitespace-nowrap text-sm leading-5 text-gray-500">
{!! \App\Models\Payment::badgeForStatus($payment->status_id) !!} {!! $payment->badgeForStatus() !!}
</td> </td>
<td class="px-6 py-4 whitespace-nowrap flex items-center justify-end text-sm leading-5 font-medium"> <td class="px-6 py-4 whitespace-nowrap flex items-center justify-end text-sm leading-5 font-medium">
<a href="{{ route('client.payments.show', $payment->hashed_id) }}" class="text-blue-600 hover:text-indigo-900 focus:outline-none focus:underline"> <a href="{{ route('client.payments.show', $payment->hashed_id) }}" class="text-blue-600 hover:text-indigo-900 focus:outline-none focus:underline">

View File

@ -53,7 +53,7 @@
@forelse($recurring_invoices as $recurring_invoice) @forelse($recurring_invoices as $recurring_invoice)
<tr class="bg-white group hover:bg-gray-100"> <tr class="bg-white group hover:bg-gray-100">
<td class="px-6 py-4 whitespace-nowrap text-sm leading-5 text-gray-500"> <td class="px-6 py-4 whitespace-nowrap text-sm leading-5 text-gray-500">
{!! $recurring_invoice->badgeForStatus($recurring_invoice->status_id) !!} {!! $recurring_invoice::badgeForStatus($recurring_invoice->status_id) !!}
</td> </td>
<td class="px-6 py-4 whitespace-nowrap text-sm leading-5 text-gray-500"> <td class="px-6 py-4 whitespace-nowrap text-sm leading-5 text-gray-500">
{{ $recurring_invoice->subscription->name }} {{ $recurring_invoice->subscription->name }}

View File

@ -10,6 +10,7 @@
<input type="hidden" name="payment_hash" value="{{ $payment_hash }}"> <input type="hidden" name="payment_hash" value="{{ $payment_hash }}">
<input type="hidden" name="company_gateway_id" value="{{ $gateway->company_gateway->id }}"> <input type="hidden" name="company_gateway_id" value="{{ $gateway->company_gateway->id }}">
<input type="hidden" name="gateway_response" id="gateway_response"> <input type="hidden" name="gateway_response" id="gateway_response">
<input type="hidden" name="gateway_type_id" id="gateway_type_id" value="{{ $gateway_type_id }}">
<input type="hidden" name="amount_with_fee" id="amount_with_fee" value="{{ $total['amount_with_fee'] }}"/> <input type="hidden" name="amount_with_fee" id="amount_with_fee" value="{{ $total['amount_with_fee'] }}"/>
</form> </form>
@ -23,52 +24,62 @@
@endsection @endsection
@push('footer') @push('footer')
<script src="https://www.paypal.com/sdk/js?enable-funding={!! $funding_options !!}&disable-funding=credit&components=buttons,hosted-fields,funding-eligibility&intent=capture&client-id={!! $client_id !!}" data-client-token="{!! $token !!}" data-partner-attribution-id="invoiceninja_SP_PPCP">
</script>
<script src="https://www.paypal.com/sdk/js?client-id={!! $client_id !!}&currency={!! $currency !!}&components=buttons,funding-eligibility&intent=capture&enable-funding={!! $funding_source !!}" data-partner-attribution-id="invoiceninja_SP_PPCP"></script>
<div id="paypal-button-container"></div>
<script> <script>
paypal.Buttons({ //&buyer-country=US&currency=USD&enable-funding=venmo
fundingSource: "{{ $funding_options }}", const fundingSource = "{!! $funding_source !!}";
env: "{{ $gateway->company_gateway->getConfigField('testMode') ? 'sandbox' : 'production' }}", const clientId = "{{ $client_id }}";
client: { const orderId = "{!! $order_id !!}";
@if($gateway->company_gateway->getConfigField('testMode')) const environment = "{{ $gateway->company_gateway->getConfigField('testMode') ? 'sandbox' : 'production' }}";
sandbox: "{{ $gateway->company_gateway->getConfigField('clientId') }}"
@else
production: "{{ $gateway->company_gateway->getConfigField('clientId') }}"
@endif
},
createOrder: function(data, actions) {
return "{!! $order_id !!}"
},
onCancel: function() {
window.location.href = "/client/invoices/";
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) { paypal.Buttons({
env: environment,
document.getElementById("gateway_response").value =JSON.stringify( details ); fundingSource: fundingSource,
document.getElementById("server_response").submit(); client: clientId,
createOrder: function(data, actions) {
return orderId;
},
onApprove: function(data, actions) {
}); var errorDetail = Array.isArray(data.details) && data.details[0];
if (errorDetail && ['INSTRUMENT_DECLINED', 'PAYER_ACTION_REQUIRED'].includes(errorDetail.issue)) {
return actions.restart();
}
}, document.getElementById("gateway_response").value =JSON.stringify( data );
onError: function(err) { document.getElementById("server_response").submit();
console.log(err);
}, },
onClick: function (){ onCancel: function() {
document.getElementById('paypal-button-container').hidden = true; window.location.href = "/client/invoices/";
} },
onError: function(error) {
document.getElementById("gateway_response").value = error;
document.getElementById("server_response").submit();
},
onClick: function (){
if(fundingSource != 'card')
document.getElementById('paypal-button-container').hidden = true;
}
}).render('#paypal-button-container').catch(function(err) { }).render('#paypal-button-container').catch(function(err) {
document.getElementById('errors').textContent = err; document.getElementById('errors').textContent = err;
document.getElementById('errors').hidden = false; document.getElementById('errors').hidden = false;
}) });
document.getElementById("server_response").addEventListener('submit', (e) => {
if (document.getElementById("server_response").classList.contains('is-submitting')) {
e.preventDefault();
}
document.getElementById("server_response").classList.add('is-submitting');
});
</script> </script>
@endpush @endpush

View File

@ -21,7 +21,7 @@
{{ ctrans('texts.status') }} {{ ctrans('texts.status') }}
</dt> </dt>
<div class="mt-1 text-sm leading-5 text-gray-900 sm:mt-0 sm:col-span-2"> <div class="mt-1 text-sm leading-5 text-gray-900 sm:mt-0 sm:col-span-2">
{!! \App\Models\Payment::badgeForStatus($payment->status_id) !!} {!! $payment->badgeForStatus() !!}
</div> </div>
</div> </div>
@endif @endif

View File

@ -51,9 +51,14 @@
document.addEventListener('livewire:init', () => { document.addEventListener('livewire:init', () => {
Livewire.on('beforePaymentEventsCompleted', () => document.getElementById('payment-method-form').submit()); Livewire.on('beforePaymentEventsCompleted', () => {
setTimeout(() => {
document.getElementById('payment-method-form').submit()
}, 2000);
});
}); });
</script> </script>
@endpush @endpush