SettingsController::postPaymentWithRazorpay()   F
last analyzed

Complexity

Conditions 13
Paths 600

Size

Total Lines 115
Code Lines 88

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 88
dl 0
loc 115
rs 2.6662
c 1
b 0
f 1
cc 13
nc 600
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace App\Plugins\Razorpay\Controllers;
4
5
use App\ApiKey;
6
use App\Http\Controllers\Controller;
7
use App\Model\Common\Setting;
8
use App\Model\Common\StatusSetting;
9
use App\Plugins\Razorpay\Model\RazorpayPayment;
10
use Cartalyst\Stripe\Laravel\Facades\Stripe;
11
use Illuminate\Http\Request;
12
use Razorpay\Api\Api;
13
use Schema;
14
use Validator;
15
16
class SettingsController extends Controller
17
{
18
    public function __construct()
19
    {
20
        $this->middleware('auth');
21
        $this->middleware('admin', ['except'=>['postPaymentWithRazorpay']]);
22
    }
23
24
    public function Settings()
25
    {
26
        try {
27
            if (! Schema::hasTable('razorpay')) {
28
                Schema::create('razorpay', function ($table) {
29
                    $table->increments('id');
30
                    $table->string('image_url');
31
                    $table->string('processing_fee');
32
                    $table->string('base_currency');
33
                    $table->string('currencies');
34
                    $table->timestamps();
35
                });
36
            }
37
38
            $razorpay1 = new RazorpayPayment();
39
            // //dd($ccavanue);
40
            $razorpay = $razorpay1->where('id', '1')->first();
41
42
            if (! $razorpay) {
43
                \Artisan::call('db:seed', ['--class' => 'database\\seeds\\RazorpaySupportedCurrencySeeder', '--force' => true]);
44
            }
45
            $allCurrencies = RazorpayPayment::pluck('currencies', 'id')->toArray();
46
            $rzpkey = new ApiKey();
47
            $rzpKeys = $rzpkey->select('rzp_key', 'rzp_secret', 'apilayer_key')->first();
48
            $baseCurrency = RazorpayPayment::pluck('base_currency')->toArray();
49
            $path = app_path().'/Plugins/Razorpay/views';
50
            \View::addNamespace('plugins', $path);
51
52
            return view('plugins::settings', compact('razorpay', 'baseCurrency', 'allCurrencies', 'rzpKeys'));
53
        } catch (\Exception $ex) {
54
            return redirect()->back()->with('fails', $ex->getMessage());
55
        }
56
    }
57
58
    public function postSettings(Request $request)
59
    {
60
        $this->validate($request, [
61
            'business'    => 'required',
62
            'cmd'         => 'required',
63
            'paypal_url'  => 'required|url',
64
            'success_url' => 'url',
65
            'cancel_url'  => 'url',
66
            'notify_url'  => 'url',
67
            'currencies'  => 'required',
68
        ]);
69
70
        try {
71
            $ccavanue1 = new Paypal();
72
            $ccavanue = $ccavanue1->where('id', '1')->first();
73
            $ccavanue->fill($request->input())->save();
74
75
            return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
76
        } catch (\Exception $ex) {
77
            return redirect()->back()->with('fails', $ex->getMessage());
78
        }
79
    }
80
81
    public function changeBaseCurrency(Request $request)
82
    {
83
        $baseCurrency = Stripe::where('id', $request->input('b_currency'))->pluck('currencies')->first();
84
        $allCurrencies = Stripe::select('base_currency', 'id')->get();
85
        foreach ($allCurrencies as $currencies) {
86
            Stripe::where('id', $currencies->id)->update(['base_currency'=>$baseCurrency]);
87
        }
88
89
        return ['message' => 'success', 'update'=>'Base Currency Updated'];
90
    }
91
92
    /*
93
    * Update Razorpay Details In Database
94
    */
95
    public function updateApiKey(Request $request)
96
    {
97
        try {
98
            $rzp_key = $request->input('rzp_key');
99
            $rzp_secret = $request->input('rzp_secret');
100
            $api = new Api($rzp_key, $rzp_secret);
101
            $orderData = [
102
                'receipt'         => 3456,
103
                'amount'          => 2000 * 100, // 2000 rupees in paise
104
                'currency'        => 'INR',
105
                'payment_capture' => 1, // auto capture
106
            ];
107
108
            $razorpayOrder = $api->order->create($orderData);
109
            $status = $request->input('status');
110
            $apilayer_key = $request->input('apilayer_key');
111
            StatusSetting::find(1)->update(['rzp_status'=>$status]);
112
            ApiKey::find(1)->update(['rzp_key'=>$rzp_key, 'rzp_secret'=>$rzp_secret, 'apilayer_key'=>$apilayer_key]);
113
114
            return successResponse(['success'=>'true', 'message'=>'Razorpay Settings updated successfully']);
115
        } catch (\Razorpay\Api\Errors\BadRequestError $e) {
116
            return errorResponse($e->getMessage());
117
        } catch (\Exception $e) {
118
            return errorResponse($e->getMessage());
119
        }
120
121
        // $apilayer_key = $request->input('apilayer_key');
122
        // $status = $request->input('status');
123
        // StatusSetting::find(1)->update(['rzp_status'=>$status]);
124
        // ApiKey::find(1)->update(['rzp_key'=>$rzp_key, 'rzp_secret'=>$rzp_secret, 'apilayer_key'=>$apilayer_key]);
125
126
        // return successResponse(['success'=>'true', 'message'=>'Razorpay Settings updated successfully']);
127
    }
128
129
    /**
130
     * success response method.
131
     *
132
     * @return \Illuminate\Http\Response
133
     */
134
    public function postPaymentWithRazorpay(Request $request)
135
    {
136
        $validator = Validator::make($request->all(), [
137
        ]);
138
        $input = $request->all();
139
        $validation = [
140
            'card_no' => 'required',
141
            'exp_month' => 'required',
142
            'exp_year' => 'required',
143
            'cvv' => 'required',
144
        ];
145
146
        $this->validate($request, $validation);
147
        $stripeSecretKey = ApiKey::pluck('stripe_secret')->first();
148
        $stripe = Stripe::make($stripeSecretKey);
149
        try {
150
            $invoice = \Session::get('invoice');
151
            $invoiceTotal = \Session::get('totalToBePaid');
152
            $amount = rounding(\Cart::getTotal());
153
            if (! $amount) {//During renewal
154
                if (rounding($request->input('amount')) != rounding($invoiceTotal)) {
155
                    throw new \Exception('Invalid modification of data');
156
                }
157
                $amount = rounding($request->input('amount'));
158
            }
159
            $stripeSecretKey = ApiKey::pluck('stripe_secret')->first();
160
            $stripe = Stripe::make($stripeSecretKey);
161
            $token = $stripe->tokens()->create([
162
                'card' => [
163
                    'number'    => $request->get('card_no'),
164
                    'exp_month' => $request->get('exp_month'),
165
                    'exp_year'  => $request->get('exp_year'),
166
                    'cvc'       => $request->get('cvv'),
167
                ],
168
            ]);
169
            if (! isset($token['id'])) {
170
                \Session::put('error', 'The Stripe Token was not generated correctly');
171
172
                return redirect()->route('stripform');
173
            }
174
            $customer = $stripe->customers()->create([
175
                'name' => \Auth::user()->first_name.' '.\Auth::user()->last_name,
176
                'email' => \Auth::user()->email,
177
                'address' => [
178
                    'line1' => \Auth::user()->address,
179
                    'postal_code' => \Auth::user()->zip,
180
                    'city' => \Auth::user()->town,
181
                    'state' => \Auth::user()->state,
182
                    'country' => \Auth::user()->country,
183
                ],
184
            ]);
185
            $stripeCustomerId = $customer['id'];
186
            $currency = strtolower(\Auth::user()->currency);
187
            $card = $stripe->cards()->create($stripeCustomerId, $token['id']);
188
            $charge = $stripe->charges()->create([
189
                'customer' => $customer['id'],
190
                'currency' => $currency,
191
                'amount'   =>$amount,
192
                'description' => 'Add in wallet',
193
            ]);
194
            if ($charge['status'] == 'succeeded') {
195
                //Change order Status as Success if payment is Successful
196
                $stateCode = \Auth::user()->state;
197
                $cont = new \App\Http\Controllers\RazorpayController();
198
                $state = $cont->getState($stateCode);
199
                $currency = $cont->getCurrency();
200
201
                $control = new \App\Http\Controllers\Order\RenewController();
202
                //After Regular Payment
203
                if ($control->checkRenew() === false) {
204
                    $checkout_controller = new \App\Http\Controllers\Front\CheckoutController();
205
                    $checkout_controller->checkoutAction($invoice);
206
207
                    $view = $cont->getViewMessageAfterPayment($invoice, $state, $currency);
208
                    $status = $view['status'];
209
                    $message = $view['message'];
210
                } else {
211
                    //Afer Renew
212
                    $control->successRenew($invoice);
213
                    $payment = new \App\Http\Controllers\Order\InvoiceController();
214
                    $payment->postRazorpayPayment($invoice);
215
                    if ($invoice->grand_total && emailSendingStatus()) {
216
                        $this->sendPaymentSuccessMailtoAdmin($invoice->currency, $invoice->grand_total, \Auth::user(), $invoice->invoiceItem()->first()->product_name);
217
                    }
218
                    $view = $cont->getViewMessageAfterRenew($invoice, $state, $currency);
219
                    $status = $view['status'];
220
                    $message = $view['message'];
221
                }
222
                \Session::forget('items');
223
                \Session::forget('code');
224
                \Session::forget('codevalue');
225
                \Session::forget('totalToBePaid');
226
                \Session::forget('invoice');
227
                \Cart::removeCartCondition('Processing fee');
228
229
                return redirect('checkout')->with($status, $message);
230
            } else {
231
                return redirect('checkout')->with('fails', 'Your Payment was declined. Please try making payment with other gateway');
232
            }
233
        } catch (\Cartalyst\Stripe\Exception\ApiLimitExceededException | \Cartalyst\Stripe\Exception\BadRequestException | \Cartalyst\Stripe\Exception\MissingParameterException | \Cartalyst\Stripe\Exception\NotFoundException | \Cartalyst\Stripe\Exception\ServerErrorException | \Cartalyst\Stripe\Exception\StripeException | \Cartalyst\Stripe\Exception\UnauthorizedException $e) {
234
            if (emailSendingStatus()) {
235
                $this->sendFailedPaymenttoAdmin($request['amount'], $e->getMessage());
236
            }
237
238
            return redirect('checkout')->with('fails', 'Your Payment was declined. '.$e->getMessage().'. Please try again or try the other gateway');
239
        } catch (\Cartalyst\Stripe\Exception\CardErrorException $e) {
240
            if (emailSendingStatus()) {
241
                $this->sendFailedPaymenttoAdmin($request['amount'], $e->getMessage());
242
            }
243
            \Session::put('amount', $request['amount']);
244
            \Session::put('error', $e->getMessage());
245
246
            return redirect()->route('checkout');
247
        } catch (\Exception $e) {
248
            return redirect('checkout')->with('fails', 'Your payment was declined. '.$e->getMessage().'. Please try again or try the other gateway.');
249
        }
250
    }
251
252
    public static function sendFailedPaymenttoAdmin($amount, $exceptionMessage)
253
    {
254
        $setting = Setting::find(1);
255
        $paymentFailData = 'Payment for'.' '.'of'.' '.\Auth::user()->currency.' '.$amount.' '.'failed by'.' '.\Auth::user()->first_name.' '.\Auth::user()->last_name.' '.'. User Email:'.' '.\Auth::user()->email.'<br>'.'Reason:'.$exceptionMessage;
256
257
        $mail = new \App\Http\Controllers\Common\PhpMailController();
258
        $mail->sendEmail($setting->email, $setting->company_email, $paymentFailData, 'Payment failed ');
259
    }
260
261
    public static function sendPaymentSuccessMailtoAdmin($currency, $total, $user, $productName)
262
    {
263
        $setting = Setting::find(1);
264
        $templateController = new \App\Http\Controllers\Common\TemplateController();
265
        $paymentSuccessdata = 'Payment for'.' '.$productName.' '.'of'.' '.$currency.' '.$total.' '.'successful by'.' '.$user->first_name.' '.$user->last_name.' '.'Email:'.' '.$user->email;
266
267
        $mail = new \App\Http\Controllers\Common\PhpMailController();
268
        $mail->sendEmail($setting->email, $setting->company_email, $paymentSuccessdata, 'Payment Successful ');
269
    }
270
}
271