Skip to content

Commit

Permalink
[Fix/Features] CSRF Ignoring Routes support & Fix Invoice creation on…
Browse files Browse the repository at this point in the history
… webhook (#640)
  • Loading branch information
1day2die authored Jan 22, 2023
2 parents b89b03d + 8c78a00 commit c32bfc1
Show file tree
Hide file tree
Showing 10 changed files with 135 additions and 139 deletions.
12 changes: 12 additions & 0 deletions app/Extensions/PaymentGateways/PayPal/config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

namespace App\Extensions\PaymentGateways\PayPal;

function getConfig()
{
return [
"name" => "PayPal",
"description" => "PayPal payment gateway",
"RoutesIgnoreCsrf" => [],
];
}
46 changes: 3 additions & 43 deletions app/Extensions/PaymentGateways/PayPal/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,10 @@
use App\Events\UserUpdateCreditsEvent;
use App\Models\PartnerDiscount;
use App\Models\Payment;
use App\Models\Product;
use App\Models\ShopProduct;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\ProductionEnvironment;
Expand All @@ -30,6 +27,7 @@ function PaypalPay(Request $request)
/** @var User $user */
$user = Auth::user();
$shopProduct = ShopProduct::findOrFail($request->shopProduct);
$discount = PartnerDiscount::getDiscount();

// create a new payment
$payment = Payment::create([
Expand All @@ -39,7 +37,7 @@ function PaypalPay(Request $request)
'type' => $shopProduct->type,
'status' => 'open',
'amount' => $shopProduct->quantity,
'price' => $shopProduct->price - ($shopProduct->price * PartnerDiscount::getDiscount() / 100),
'price' => $shopProduct->price - ($shopProduct->price * $discount / 100),
'tax_value' => $shopProduct->getTaxValue(),
'tax_percent' => $shopProduct->getTaxPercent(),
'total_price' => $shopProduct->getTotalPrice(),
Expand All @@ -54,7 +52,7 @@ function PaypalPay(Request $request)
"purchase_units" => [
[
"reference_id" => uniqid(),
"description" => $shopProduct->display . (PartnerDiscount::getDiscount() ? (" (" . __('Discount') . " " . PartnerDiscount::getDiscount() . '%)') : ""),
"description" => $shopProduct->display . ($discount ? (" (" . __('Discount') . " " . $discount . '%)') : ""),
"amount" => [
"value" => $shopProduct->getTotalPrice(),
'currency_code' => strtoupper($shopProduct->currency_code),
Expand Down Expand Up @@ -176,41 +174,3 @@ function getPaypalClientSecret()
{
return env('APP_ENV') == 'local' ? config("SETTINGS::PAYMENTS:PAYPAL:SANDBOX_SECRET") : config("SETTINGS::PAYMENTS:PAYPAL:SECRET");
}
function getPayPalConfig()
{
return [
"name" => "PayPal",
"description" => "PayPal payment gateway",
"settings" => [
"mode" => [
"type" => "select",
"label" => "Mode",
"value" => config("APP_ENV") == 'local' ? "sandbox" : "live",
"options" => [
"sandbox" => "Sandbox",
"live" => "Live",
],
],
"CLIENT_ID" => [
"type" => "text",
"label" => "PayPal Client ID",
"value" => config("SETTINGS::PAYMENTS:PAYPAL:CLIENT_ID"),
],
"SECRET" => [
"type" => "text",
"label" => "PayPal Secret",
"value" => config("SETTINGS::PAYMENTS:PAYPAL:SECRET"),
],
"SANDBOX_CLIENT_ID" => [
"type" => "text",
"label" => "PayPal Sandbox Client ID",
"value" => config("SETTINGS::PAYMENTS:PAYPAL:SANDBOX_CLIENT_ID"),
],
"SANDBOX_SECRET" => [
"type" => "text",
"label" => "PayPal Sandbox Secret",
"value" => config("SETTINGS::PAYMENTS:PAYPAL:SANDBOX_SECRET"),
],
],
];
}
14 changes: 14 additions & 0 deletions app/Extensions/PaymentGateways/Stripe/config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace App\Extensions\PaymentGateways\Stripe;

function getConfig()
{
return [
"name" => "Stripe",
"description" => "Stripe payment gateway",
"RoutesIgnoreCsrf" => [
"payment/StripeWebhooks",
],
];
}
63 changes: 17 additions & 46 deletions app/Extensions/PaymentGateways/Stripe/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,19 @@
use App\Events\UserUpdateCreditsEvent;
use App\Models\PartnerDiscount;
use App\Models\Payment;
use App\Models\Product;
use App\Models\ShopProduct;
use App\Models\User;
use App\Notifications\ConfirmPaymentNotification;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;
use Stripe\Exception\SignatureVerificationException;
use Stripe\Stripe;
use Stripe\StripeClient;




/**
* @param Request $request
* @param ShopProduct $shopProduct
Expand All @@ -34,6 +32,8 @@ function StripePay(Request $request)
return;
}

$discount = PartnerDiscount::getDiscount();


// create payment
$payment = Payment::create([
Expand All @@ -43,7 +43,7 @@ function StripePay(Request $request)
'type' => $shopProduct->type,
'status' => 'open',
'amount' => $shopProduct->quantity,
'price' => $shopProduct->price - ($shopProduct->price * PartnerDiscount::getDiscount() / 100),
'price' => $shopProduct->price - ($shopProduct->price * $discount / 100),
'tax_value' => $shopProduct->getTaxValue(),
'total_price' => $shopProduct->getTotalPrice(),
'tax_percent' => $shopProduct->getTaxPercent(),
Expand All @@ -58,7 +58,7 @@ function StripePay(Request $request)
'price_data' => [
'currency' => $shopProduct->currency_code,
'product_data' => [
'name' => $shopProduct->display . (PartnerDiscount::getDiscount() ? (' (' . __('Discount') . ' ' . PartnerDiscount::getDiscount() . '%)') : ''),
'name' => $shopProduct->display . ($discount ? (' (' . __('Discount') . ' ' . $discount . '%)') : ''),
'description' => $shopProduct->description,
],
'unit_amount_decimal' => round($shopProduct->getPriceAfterDiscount() * 100, 2),
Expand All @@ -82,6 +82,11 @@ function StripePay(Request $request)
'payment_method_types' => str_getcsv(config('SETTINGS::PAYMENTS:STRIPE:METHODS')),
'success_url' => route('payment.StripeSuccess', ['payment' => $payment->id]) . '&session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => route('payment.Cancel'),
'payment_intent_data' => [
'metadata' => [
'payment_id' => $payment->id,
],
],
]);

Redirect::to($request->url)->send();
Expand All @@ -98,6 +103,8 @@ function StripeSuccess(Request $request)
$shopProduct = ShopProduct::findOrFail($payment->shop_item_product_id);


Redirect::route('home')->with('success', 'Please wait for success')->send();

$stripeClient = getStripeClient();
try {
//get stripe data
Expand Down Expand Up @@ -162,16 +169,17 @@ function StripeSuccess(Request $request)
function handleStripePaymentSuccessHook($paymentIntent)
{
try {
// Get payment db entry
$payment = Payment::where('payment_id', $paymentIntent->id)->first();
$payment = Payment::where('id', $paymentIntent->metadata->payment_id)->with('user')->first();
$user = User::where('id', $payment->user_id)->first();
$shopProduct = ShopProduct::findOrFail($payment->shop_item_product_id);

if ($paymentIntent->status == 'succeeded' && $payment->status == 'processing') {


//update payment db entry status
$payment->update(['status' => 'paid']);
$payment->update([
'payment_id' => $payment->payment_id ?? $paymentIntent->id,
'status' => 'paid'
]);

//payment notification
$user->notify(new ConfirmPaymentNotification($payment));
Expand Down Expand Up @@ -363,40 +371,3 @@ function checkPriceAmount($amount, $currencyCode, $payment_method)
];
return $amount >= $minimums[$currencyCode][$payment_method];
}

function getStripeConfig()
{
return [
"name" => "Stripe",
"description" => "Stripe payment gateway",
"mode" => [
"type" => "select",
"label" => "Mode",
"value" => config("APP_ENV") == 'local' ? "sandbox" : "live",
"options" => [
"sandbox" => "Sandbox",
"live" => "Live",
],
],
"TEST_SECRET" => [
"type" => "text",
"label" => "Test Secret Key",
"value" => config("SETTINGS::PAYMENTS:STRIPE:TEST_SECRET"),
],
"SECRET" => [
"type" => "text",
"label" => "Live Secret Key",
"value" => config("SETTINGS::PAYMENTS:STRIPE:SECRET"),
],
"ENDPOINT_TEST_SECRET" => [
"type" => "text",
"label" => "Test Endpoint Secret",
"value" => config("SETTINGS::PAYMENTS:STRIPE:ENDPOINT_TEST_SECRET"),
],
"ENDPOINT_SECRET" => [
"type" => "text",
"label" => "Live Endpoint Secret",
"value" => config("SETTINGS::PAYMENTS:STRIPE:ENDPOINT_SECRET"),
],
];
}
87 changes: 62 additions & 25 deletions app/Helpers/ExtensionHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,44 +4,81 @@

class ExtensionHelper
{
public static function getExtensionConfig($extensionName, $nameSpace)
/**
* Get a config of an extension by its name
* @param string $extensionName
* @param string $configname
*/
public static function getExtensionConfig(string $extensionName, string $configname)
{
$extension = app_path() . '/Extensions/' . $nameSpace . "/" . $extensionName . "/index.php";
// Check if extension exists
if (!file_exists($extension)) {
return null;
}
$extensions = ExtensionHelper::getAllExtensions();

// call the getConfig function from the index.php file of the extension
$config = include_once $extension;
// call the getConfig function of the config file of the extension like that
// call_user_func("App\\Extensions\\PaymentGateways\\Stripe" . "\\getConfig");
foreach ($extensions as $extension) {
if (!(basename($extension) == $extensionName)) {
continue;
}

// Check if the getConfig function exists
if (!function_exists('get' . $extensionName . 'Config')) {
return null;
}
$configFile = $extension . '/config.php';
if (file_exists($configFile)) {
include_once $configFile;
$config = call_user_func('App\\Extensions\\' . basename(dirname($extension)) . '\\' . basename($extension) . "\\getConfig");
}

$config = call_user_func('get' . $extensionName . 'Config');

// Check if the getConfig function returned an array
if (!is_array($config)) {
return null;
if (isset($config[$configname])) {
return $config[$configname];
}
}

return $config;
return null;
}

public static function getPayMethod($extensionName, $nameSpace)
public static function getAllCsrfIgnoredRoutes()
{
// return the payment method of the extension to be used elsewhere
// for example in the payment controller
// the function starts with the name of the extension and ends with Pay
$extensions = ExtensionHelper::getAllExtensions();

$routes = [];
foreach ($extensions as $extension) {
$configFile = $extension . '/config.php';
if (file_exists($configFile)) {
include_once $configFile;
$config = call_user_func('App\\Extensions\\' . basename(dirname($extension)) . '\\' . basename($extension) . "\\getConfig");
}

if (isset($config['RoutesIgnoreCsrf'])) {
$routes = array_merge($routes, $config['RoutesIgnoreCsrf']);
}

// add extension/ infront of every route
foreach ($routes as $key => $route) {
$routes[$key] = 'extensions/' . $route;
}
}

$config = self::getExtensionConfig($extensionName, $nameSpace);
return $routes;
}

if ($config == null) {
return null;
/**
* Get all extensions
* @return array
*/
public static function getAllExtensions()
{
$extensionNamespaces = glob(app_path() . '/Extensions/*', GLOB_ONLYDIR);
$extensions = [];
foreach ($extensionNamespaces as $extensionNamespace) {
$extensions = array_merge($extensions, glob($extensionNamespace . '/*', GLOB_ONLYDIR));
}

return $config['payMethod'];
return $extensions;
}

public static function getAllExtensionsByNamespace(string $namespace)
{
$extensions = glob(app_path() . '/Extensions/' . $namespace . '/*', GLOB_ONLYDIR);

return $extensions;
}
}
20 changes: 9 additions & 11 deletions app/Http/Controllers/Admin/PaymentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,26 +38,24 @@ public function index()
*/
public function checkOut(ShopProduct $shopProduct)
{
// get all payment gateway extensions
$extensions = glob(app_path() . '/Extensions/PaymentGateways/*', GLOB_ONLYDIR);
$extensions = ExtensionHelper::getAllExtensionsByNamespace('PaymentGateways');

// build a paymentgateways array that contains the routes for the payment gateways and the image path for the payment gateway which lays in public/images/Extensions/PaymentGateways with the extensionname in lowercase
$paymentGateways = [];
foreach ($extensions as $extension) {
$extensionName = basename($extension);
$config = ExtensionHelper::getExtensionConfig($extensionName, 'PaymentGateways');
if ($config) {
$payment = new \stdClass();
$payment->name = $config['name'];
$payment->image = asset('images/Extensions/PaymentGateways/' . strtolower($extensionName) . '_logo.png');
$paymentGateways[] = $payment;
}
$payment = new \stdClass();
$payment->name = ExtensionHelper::getExtensionConfig($extensionName, 'name');
$payment->image = asset('images/Extensions/PaymentGateways/' . strtolower($extensionName) . '_logo.png');
$paymentGateways[] = $payment;
}

$discount = PartnerDiscount::getDiscount();

return view('store.checkout')->with([
'product' => $shopProduct,
'discountpercent' => PartnerDiscount::getDiscount(),
'discountvalue' => PartnerDiscount::getDiscount() * $shopProduct->price / 100,
'discountpercent' => $discount,
'discountvalue' => $discount * $shopProduct->price / 100,
'discountedprice' => $shopProduct->getPriceAfterDiscount(),
'taxvalue' => $shopProduct->getTaxValue(),
'taxpercent' => $shopProduct->getTaxPercent(),
Expand Down
Loading

0 comments on commit c32bfc1

Please sign in to comment.