Completed
Push — master ( c8c3d9...7f8d6c )
by Kazi Mainuddin
01:59
created

PaymentController::getFormDataArray()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 1
1
<?php
2
namespace Tzsk\Payu\Controllers;
3
4
5
use App\Http\Controllers\Controller;
6
use Illuminate\Http\Request;
7
use Illuminate\Support\Facades\Cache;
8
use Illuminate\Support\Facades\Validator;
9
use Tzsk\Payu\Model\PayuPayment;
10
use Tzsk\Payu\ProcessPayment;
11
12
class PaymentController extends Controller
13
{
14
    /**
15
     * Got to payment.
16
     *
17
     * @param Request $request
18
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
19
     */
20
    public function index(Request $request)
21
    {
22
        $payment = $this->getPaymentFormInformation($request);
23
24
        return view('tzsk::payment_form', compact('payment'));
25
    }
26
27
    /**
28
     * After payment it will return here.
29
     *
30
     * @param Request $request
31
     * @return \Illuminate\Http\RedirectResponse
32
     */
33
    public function payment(Request $request)
34
    {
35
        $attributes = $request->only([
36
            'txnid', 'mihpayid', 'firstname', 'email', 'phone', 'amount', 'discount',
37
            'net_amount_debit', 'data', 'status', 'unmappedstatus', 'mode', 'bank_ref_num',
38
            'bankcode', 'cardnum', 'name_on_card', 'issuing_bank', 'card_type'
39
        ]);
40
        $attributes['data'] = json_encode($request->all());
41
        $process = new ProcessPayment($request);
42
        $attributes['status'] = $process->getStatus();
43
44
        $this->generatePaymentObject($attributes);
45
46
        return redirect()->to(base64_decode($request->callback));
47
    }
48
49
    /**
50
     * @param  Request $request
51
     * @return object
52
     * @throws \Exception
53
     */
54
    protected  function getPaymentFormInformation(Request $request)
55
    {
56
        $form_fields = $this->getFormFields($request);
57
58
        $prefix = (config('payu.env') == 'secure') ? 'secure' : 'test';
59
        $url = "https://{$prefix}.".config('payu.endpoint');
60
61
        $payment = (object) ['fields' => $form_fields, 'url' => $url];
62
63
        return $payment;
64
    }
65
66
    /**
67
     * @param Request $request
68
     * @return string
69
     */
70
    protected function getHashChecksum(Request $request)
71
    {
72
        $fields = array_merge(config('payu.required_fields'), config('payu.optional_fields'));
73
74
        $hash_array = [];
75
        foreach (collect($fields)->flip()->except(['phone'])->flip() as $field) {
76
            $hash_array[] = $request->has($field) ? $request->get($field) : "";
77
        }
78
79
        $checksum_array = array_merge([config('payu.key')], $hash_array, [config('payu.salt')]);
80
81
        $hash = hash('sha512', implode('|', $checksum_array));
82
83
        return $hash;
84
    }
85
86
    /**
87
     * @param Request $request
88
     * @return array
89
     */
90
    protected function validateRequest(Request $request)
91
    {
92
        list($validation, $data) = $this->getValidationData($request);
93
94
        $validator = Validator::make($request->all(), $validation);
95
96
        if ($validator->fails()) {
97
            throw new \InvalidArgumentException($validator->errors()->first());
98
        }
99
100
        return $data;
101
    }
102
103
    /**
104
     * @param  Request $request
105
     * @return array
106
     */
107
    protected function getValidationData(Request $request)
108
    {
109
        $validation = collect(array_flip(config('payu.required_fields')))->map(function($value) {
0 ignored issues
show
Unused Code introduced by
The parameter $value is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
110
            return 'required';
111
        });
112
113
        $data = $this->getFormDataArray($request);
114
115
        return [$validation, $data];
116
    }
117
118
    /**
119
     * Generate the payment model Object for use.
120
     *
121
     * @param $attributes
122
     */
123
    protected function generatePaymentObject($attributes)
124
    {
125
        $model = Cache::get('tzsk_model');
126
127
        if (config('payu.driver') == 'database') {
128
            $payment_instance = PayuPayment::create($attributes);
129
130
            if (!empty($model)) {
131
                $payment_instance->fill([
132
                    'payable_id' => $model->id,
133
                    'payable_type' => get_class($model)
134
                ])->save();
135
            }
136
137
            $payment = $payment_instance->id;
138
139
        } else {
140
            $payment = $attributes;
141
        }
142
143
        Cache::put('tzsk_payment', $payment, 5);
144
    }
145
146
    /**
147
     * Get the form data array.
148
     *
149
     * @param Request $request
150
     * @return array
151
     */
152
    private function getFormDataArray(Request $request)
153
    {
154
        $data = [];
155
        $items = collect(config('payu.required_fields'))->merge(config('payu.optional_fields'))
156
            ->merge(config('payu.additional_fields'));
157
158
        foreach ($items as $item) {
159
            $request->has($item) ? $data[$item] = $request->get($item) : null;
160
        }
161
162
        return $data;
163
    }
164
165
    /**
166
     * Get Status url.
167
     *
168
     * @return mixed
169
     * @throws \Exception
170
     */
171
    private function getStatusUrl()
172
    {
173
        $status_url = Cache::get('tzsk_status_url');
174
175
        if (empty($status_url)) {
176
            throw new \Exception("There is no Redirect URL specified.");
177
        }
178
179
        return urlencode(base64_encode($status_url));
180
    }
181
182
    /**
183
     * @param Request $request
184
     * @return array
185
     */
186
    protected function getFormFields(Request $request)
187
    {
188
        $data = Cache::get('tzsk_data');
189
        $status_url = $this->getStatusUrl();
190
191
        $request->replace($data);
192
        $validation = $this->validateRequest($request);
193
        $hash = $this->getHashChecksum($request);
194
195
        $redirect = collect(config('payu.redirect'))->map(function ($value) use ($request, $status_url) {
196
            $separator = str_contains($value, '?') ? '&' : '?';
197
            return url($value . $separator . 'callback=' . $status_url);
198
        })->all();
199
200
        $form_fields = array_merge(['key' => config('payu.key'), 'hash' => $hash],
201
            array_merge($redirect, $validation));
202
203
        return $form_fields;
204
    }
205
206
}
207