Browse Source

feat: ✨ Migrate other payment gateways to new payment pattern

IceToast 2 years ago
parent
commit
48e5cae9a1

+ 8 - 52
app/Extensions/PaymentGateways/Mollie/MollieExtension.php

@@ -2,7 +2,7 @@
 
 
 namespace App\Extensions\PaymentGateways\Mollie;
 namespace App\Extensions\PaymentGateways\Mollie;
 
 
-use App\Helpers\AbstractExtension;
+use App\Classes\AbstractExtension;
 use App\Events\PaymentEvent;
 use App\Events\PaymentEvent;
 use App\Events\UserUpdateCreditsEvent;
 use App\Events\UserUpdateCreditsEvent;
 use App\Models\PartnerDiscount;
 use App\Models\PartnerDiscount;
@@ -37,43 +37,10 @@ class MollieExtension extends AbstractExtension
         ];
         ];
     }
     }
 
 
-    public function pay(Request $request): void
+    public static function getRedirectUrl(Payment $payment, ShopProduct $shopProduct, string $totalPriceString): string
     {
     {
         $url = 'https://api.mollie.com/v2/payments';
         $url = 'https://api.mollie.com/v2/payments';
         $settings = new MollieSettings();
         $settings = new MollieSettings();
-
-        $user = Auth::user();
-        $shopProduct = ShopProduct::findOrFail($request->shopProduct);
-        $discount = PartnerDiscount::getDiscount();
-        $couponCode = $request->input('couponCode');
-        $isValidCoupon = $this->validateCoupon($request->user(), $couponCode, $request->shopProduct);
-        $price = $shopProduct->price;
-
-        // Coupon Discount.
-        if ($isValidCoupon->getStatusCode() == 200) {
-            $price = $this->calcDiscount($price, $isValidCoupon->getData());
-        }
-
-        // Partner Discount.
-        $price = $price - ($price * $discount / 100);
-        $price = number_format($price, 2, thousands_separator: '');
-
-        // create a new payment
-        $payment = Payment::create([
-            'user_id' => $user->id,
-            'payment_id' => null,
-            'payment_method' => 'mollie',
-            'type' => $shopProduct->type,
-            'status' => 'open',
-            'amount' => $shopProduct->quantity,
-            'price' => $price,
-            'tax_value' => $shopProduct->getTaxValue(),
-            'tax_percent' => $shopProduct->getTaxPercent(),
-            'total_price' => $shopProduct->getTotalPrice(),
-            'currency_code' => $shopProduct->currency_code,
-            'shop_item_product_id' => $shopProduct->id,
-        ]);
-
         try {
         try {
             $response = Http::withHeaders([
             $response = Http::withHeaders([
                 'Content-Type' => 'application/json',
                 'Content-Type' => 'application/json',
@@ -81,10 +48,10 @@ class MollieExtension extends AbstractExtension
             ])->post($url, [
             ])->post($url, [
                 'amount' => [
                 'amount' => [
                     'currency' => $shopProduct->currency_code,
                     'currency' => $shopProduct->currency_code,
-                    'value' => $price,
+                    'value' => $totalPriceString,
                 ],
                 ],
                 'description' => "Order #{$payment->id} - " . $shopProduct->name,
                 'description' => "Order #{$payment->id} - " . $shopProduct->name,
-                'redirectUrl' => route('payment.MollieSuccess', ['couponCode' => $couponCode]),
+                'redirectUrl' => route('payment.MollieSuccess'),
                 'cancelUrl' => route('payment.Cancel'),
                 'cancelUrl' => route('payment.Cancel'),
                 'webhookUrl' => url('/extensions/payment/MollieWebhook'),
                 'webhookUrl' => url('/extensions/payment/MollieWebhook'),
                 'metadata' => [
                 'metadata' => [
@@ -94,24 +61,13 @@ class MollieExtension extends AbstractExtension
 
 
             if ($response->status() != 201) {
             if ($response->status() != 201) {
                 Log::error('Mollie Payment: ' . $response->body());
                 Log::error('Mollie Payment: ' . $response->body());
-                $payment->delete();
-
-                Redirect::route('store.index')->with('error', __('Payment failed'))->send();
-                return;
+                throw new Exception('Payment failed');
             }
             }
 
 
-            $payment->update([
-                'payment_id' => $response->json()['id'],
-            ]);
-
-            Redirect::away($response->json()['_links']['checkout']['href'])->send();
-            return;
+            return $response->json()['_links']['checkout']['href'];
         } catch (Exception $ex) {
         } catch (Exception $ex) {
             Log::error('Mollie Payment: ' . $ex->getMessage());
             Log::error('Mollie Payment: ' . $ex->getMessage());
-            $payment->delete();
-
-            Redirect::route('store.index')->with('error', __('Payment failed'))->send();
-            return;
+            throw new Exception('Payment failed');
         }
         }
     }
     }
 
 
@@ -122,7 +78,7 @@ class MollieExtension extends AbstractExtension
         $couponCode = $request->input('couponCode');
         $couponCode = $request->input('couponCode');
 
 
         if ($couponCode) {
         if ($couponCode) {
-            event(new CouponUsedEvent(new Coupon, $couponCode));
+            event(new CouponUsedEvent($couponCode));
         }
         }
 
 
         Redirect::route('home')->with('success', 'Your payment is being processed')->send();
         Redirect::route('home')->with('success', 'Your payment is being processed')->send();

+ 0 - 1
app/Extensions/PaymentGateways/PayPal/PayPalExtension.php

@@ -156,7 +156,6 @@ class PayPalExtension extends PaymentExtension
 
 
     static function getPayPalClient(): PayPalHttpClient
     static function getPayPalClient(): PayPalHttpClient
     {
     {
-        error_log(config('app.env'));
 
 
         $environment = config('app.env') == 'local'
         $environment = config('app.env') == 'local'
             ? new SandboxEnvironment(self::getPaypalClientId(), self::getPaypalClientSecret())
             ? new SandboxEnvironment(self::getPaypalClientId(), self::getPaypalClientSecret())

+ 11 - 49
app/Extensions/PaymentGateways/Stripe/StripeExtension.php

@@ -2,7 +2,7 @@
 
 
 namespace App\Extensions\PaymentGateways\Stripe;
 namespace App\Extensions\PaymentGateways\Stripe;
 
 
-use App\Helpers\AbstractExtension;
+use App\Classes\AbstractExtension;
 use App\Events\PaymentEvent;
 use App\Events\PaymentEvent;
 use App\Events\CouponUsedEvent;
 use App\Events\CouponUsedEvent;
 use App\Events\UserUpdateCreditsEvent;
 use App\Events\UserUpdateCreditsEvent;
@@ -36,52 +36,14 @@ class StripeExtension extends AbstractExtension
         ];
         ];
     }
     }
 
 
-    /**
-     * @param  Request  $request
-     * @param  ShopProduct  $shopProduct
-     */
-    public function StripePay(Request $request)
+    public static function getRedirectUrl(Payment $payment, ShopProduct $shopProduct, string $totalPriceString): string
     {
     {
-        $user = Auth::user();
-        $shopProduct = ShopProduct::findOrFail($request->shopProduct);
-        $price = $shopProduct->price;
-
-        // check if the price is valid for stripe
-        if (!self::checkPriceAmount($shopProduct->getTotalPrice(), strtoupper($shopProduct->currency_code), 'stripe')) {
-            Redirect::route('home')->with('error', __('The product you chose can\'t be purchased with this payment method. The total amount is too small. Please buy a bigger amount or try a different payment method.'))->send();
-            return;
+        // check if the total price is valid for stripe
+        $totalPriceNumber = floatval($totalPriceString);
+        if (!self::checkPriceAmount($totalPriceNumber, strtoupper($shopProduct->currency_code), 'stripe')) {
+            throw new Exception('Invalid price amount');
         }
         }
 
 
-        $discount = PartnerDiscount::getDiscount();
-        $couponCode = $request->input('couponCode');
-        $isValidCoupon = $this->validateCoupon($request->user(), $couponCode, $request->shopProduct);
-
-        // Coupon Discount.
-        if ($isValidCoupon->getStatusCode() == 200) {
-            $price = $this->calcDiscount($price, $isValidCoupon->getData());
-        }
-
-        // Partner Discount.
-        $price = $price - ($price * $discount / 100);
-        $price = number_format($price, 2);
-
-
-        // create payment
-        $payment = Payment::create([
-            'user_id' => $user->id,
-            'payment_id' => null,
-            'payment_method' => 'stripe',
-            'type' => $shopProduct->type,
-            'status' => 'open',
-            'amount' => $shopProduct->quantity,
-            'price' => $price,
-            'tax_value' => $shopProduct->getTaxValue(),
-            'total_price' => $shopProduct->getTotalPrice(),
-            'tax_percent' => $shopProduct->getTaxPercent(),
-            'currency_code' => $shopProduct->currency_code,
-            'shop_item_product_id' => $shopProduct->id,
-        ]);
-
         $stripeClient = self::getStripeClient();
         $stripeClient = self::getStripeClient();
         $request = $stripeClient->checkout->sessions->create([
         $request = $stripeClient->checkout->sessions->create([
             'line_items' => [
             'line_items' => [
@@ -89,10 +51,10 @@ class StripeExtension extends AbstractExtension
                     'price_data' => [
                     'price_data' => [
                         'currency' => $shopProduct->currency_code,
                         'currency' => $shopProduct->currency_code,
                         'product_data' => [
                         'product_data' => [
-                            'name' => $shopProduct->display . ($discount ? (' (' . __('Discount') . ' ' . $discount . '%)') : ''),
+                            'name' => $shopProduct->display,
                             'description' => $shopProduct->description,
                             'description' => $shopProduct->description,
                         ],
                         ],
-                        'unit_amount_decimal' => $price,
+                        'unit_amount_decimal' => $totalPriceString,
                     ],
                     ],
                     'quantity' => 1,
                     'quantity' => 1,
                 ],
                 ],
@@ -110,7 +72,7 @@ class StripeExtension extends AbstractExtension
             ],
             ],
 
 
             'mode' => 'payment',
             'mode' => 'payment',
-            'success_url' => route('payment.StripeSuccess', ['payment' => $payment->id, 'couponCode' => $couponCode]) . '&session_id={CHECKOUT_SESSION_ID}',
+            'success_url' => route('payment.StripeSuccess', ['payment' => $payment->id]) . '&session_id={CHECKOUT_SESSION_ID}',
             'cancel_url' => route('payment.Cancel'),
             'cancel_url' => route('payment.Cancel'),
             'payment_intent_data' => [
             'payment_intent_data' => [
                 'metadata' => [
                 'metadata' => [
@@ -119,7 +81,7 @@ class StripeExtension extends AbstractExtension
             ],
             ],
         ]);
         ]);
 
 
-        Redirect::to($request->url)->send();
+        return $request->url;
     }
     }
 
 
     /**
     /**
@@ -302,7 +264,7 @@ class StripeExtension extends AbstractExtension
      * @return bool
      * @return bool
      * @description check if the amount is higher than the minimum amount for the stripe gateway
      * @description check if the amount is higher than the minimum amount for the stripe gateway
      */
      */
-    public static function checkPriceAmount($amount, $currencyCode, $payment_method)
+    public static function checkPriceAmount(float $amount,  string $currencyCode, string $payment_method)
     {
     {
         $minimums = [
         $minimums = [
             "USD" => [
             "USD" => [

+ 0 - 3
app/Http/Controllers/Admin/PaymentController.php

@@ -184,9 +184,6 @@ class PaymentController extends Controller
         return redirect()->away($redirectUrl);
         return redirect()->away($redirectUrl);
     }
     }
 
 
-
-
-
     /**
     /**
      * @param  Request  $request
      * @param  Request  $request
      */
      */