Completed
Push — dev ( 47cbba...685566 )
by Darko
06:35
created

BtcPaymentController::showPaypal()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
c 0
b 0
f 0
dl 0
loc 11
rs 9.9666
cc 1
nc 1
nop 0
1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\Models\User;
6
use Omnipay\Omnipay;
7
use App\Models\Settings;
8
use Illuminate\Http\Request;
9
use App\Models\PaypalPayment;
10
use Blacklight\libraries\Geary;
11
use Spatie\Permission\Models\Role;
12
13
class BtcPaymentController extends BasePageController
14
{
15
    /**
16
     * @param \Illuminate\Http\Request $request
17
     * @throws \Exception
18
     */
19
    public function show(Request $request)
20
    {
21
        $this->setPrefs();
22
        $gateway_id = env('MYCELIUM_GATEWAY_ID');
23
        $gateway_secret = env('MYCELIUM_GATEWAY_SECRET');
24
25
        $action = $request->input('action') ?? 'view';
26
        $donation = Role::query()->where('donation', '>', 0)->get(['id', 'name', 'donation', 'addyears']);
27
        $this->smarty->assign('donation', $donation);
0 ignored issues
show
Bug introduced by
The method assign() does not exist on Illuminate\Foundation\Application. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

27
        $this->smarty->/** @scrutinizer ignore-call */ 
28
                       assign('donation', $donation);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
28
29
        switch ($action) {
30
            case 'submit':
31
                $price = $request->input('price');
32
                $role = $request->input('role');
33
                $roleName = $request->input('rolename');
34
                $addYears = $request->input('addyears');
35
                $data = ['user_id' => $this->userdata->id, 'username' => $this->userdata->username, 'price' => $price, 'role' => $role, 'rolename' => $roleName, 'addyears' => $addYears];
36
                $keychain_id = random_int(0, 19);
37
                $callback_data = json_encode($data);
38
39
                $geary = new Geary($gateway_id, $gateway_secret);
40
                $order = $geary->create_order($price, $keychain_id, $callback_data);
41
42
                if ($order->payment_id) {
43
                    // Redirect to a payment gateway
44
                    $url = 'https://gateway.gear.mycelium.com/pay/'.$order->payment_id;
45
46
                    return redirect($url);
47
                }
48
                break;
49
            case 'view':
50
            default:
51
                $userId = $this->userdata->id;
0 ignored issues
show
Unused Code introduced by
The assignment to $userId is dead and can be removed.
Loading history...
52
                break;
53
        }
54
55
        $title = 'Become a supporter';
56
        $meta_title = 'Become a supporter';
57
        $meta_description = 'Become a supporter';
58
59
        $content = $this->smarty->fetch('btc_payment.tpl');
0 ignored issues
show
Bug introduced by
The method fetch() does not exist on Illuminate\Foundation\Application. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

59
        /** @scrutinizer ignore-call */ 
60
        $content = $this->smarty->fetch('btc_payment.tpl');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
60
61
        $this->smarty->assign(compact('content', 'meta_title', 'title', 'meta_description'));
62
        $this->pagerender();
63
    }
64
65
    /**
66
     * Callback data from Mycelium Gear.
67
     */
68
    public function callback()
69
    {
70
        $gateway_id = env('MYCELIUM_GATEWAY_ID');
71
        $gateway_secret = env('MYCELIUM_GATEWAY_SECRET');
72
73
        $geary = new Geary($gateway_id, $gateway_secret);
74
        $order = $geary->check_order_callback();
75
76
        // Order status was received
77
        if ($order !== false) {
78
            $callback_data = json_decode($order['callback_data'], true);
79
            $newRole = $callback_data['role'];
80
            $amount = $callback_data['price'];
0 ignored issues
show
Unused Code introduced by
The assignment to $amount is dead and can be removed.
Loading history...
81
            $addYear = $callback_data['addyears'];
82
            // If order was paid in full (2) or overpaid (4)
83
            if ((int) $order['status'] === 2 || (int) $order['status'] === 4) {
84
                User::updateUserRole($callback_data['user_id'], $newRole);
85
                User::updateUserRoleChangeDate($callback_data['user_id'], null, $addYear);
86
            }
87
        }
88
    }
89
90
    /**
91
     * @param Request $request
92
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
93
     * @throws \Exception
94
     */
95
    public function paypal(Request $request)
96
    {
97
        $this->setPrefs();
98
        $gateway = Omnipay::create('PayPal_Rest');
99
        $gateway->initialize(['clientId' => env('PAYPAL_CLIENTID'), 'secret' => env('PAYPAL_SECRET'), 'testMode' => env('PAYPAL_TEST_MODE')]);
100
        $amount = $request->input('amount');
101
102
        // Do a purchase transaction on the gateway
103
        try {
104
            $transaction = $gateway->purchase([
0 ignored issues
show
Bug introduced by
The method purchase() does not exist on Omnipay\Common\GatewayInterface. It seems like you code against a sub-type of Omnipay\Common\GatewayInterface such as Omnipay\PayPal\RestGateway or Omnipay\PayPal\ProGateway. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

104
            /** @scrutinizer ignore-call */ 
105
            $transaction = $gateway->purchase([
Loading history...
105
                'amount' => $amount,
106
                'currency' => 'USD',
107
                'description' => $this->userdata->id,
108
                'returnUrl' => 'http://homestead.test/thankyou?id='.$this->userdata->id.'&amount='.$amount,
109
                'cancelUrl' => 'http://homestead.test/payment_failed',
110
            ]);
111
            $response = $transaction->send();
112
113
            if ($response->isSuccessful()) {
114
                return redirect($response->getRedirectUrl());
115
            } elseif ($response->isRedirect()) {
116
                return $response->redirect();
117
            }
118
        } catch (\Exception $e) {
119
            echo "Exception caught while attempting authorize.\n";
120
            echo 'Exception type == '.get_class($e)."\n";
121
            echo 'Message == '.$e->getMessage()."\n";
122
        }
123
    }
124
125
    /**
126
     * @throws \Exception
127
     */
128
    public function showPaypal()
129
    {
130
        $this->setPrefs();
131
        $donation = Role::query()->where('donation', '>', 0)->get(['id', 'name', 'donation', 'addyears']);
132
        $this->smarty->assign('donation', $donation);
133
        $title = 'Become a supporter';
134
        $meta_title = 'Become a supporter';
135
        $meta_description = 'Become a supporter';
136
        $content = $this->smarty->fetch('pay_by_paypal.tpl');
137
        $this->smarty->assign(compact('content', 'meta_title', 'title', 'meta_description'));
138
        $this->pagerender();
139
    }
140
141
    /**
142
     * @param Request $request
143
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
144
     * @throws \Exception
145
     */
146
    public function paypalCallback(Request $request)
147
    {
148
        $this->setPrefs();
149
        $amount = $request->input('amount');
150
        $userId = $request->input('id');
151
152
        $role = Role::query()->where('donation', $amount)->first();
153
154
        $gateway = Omnipay::create('PayPal_Rest');
155
        $gateway->initialize(['clientId' => env('PAYPAL_CLIENTID'), 'secret' => env('PAYPAL_SECRET'), 'testMode' => env('PAYPAL_TEST_MODE')]);
156
157
        $response = $gateway->completePurchase(
0 ignored issues
show
Bug introduced by
The method completePurchase() does not exist on Omnipay\Common\GatewayInterface. It seems like you code against a sub-type of Omnipay\Common\GatewayInterface such as Omnipay\PayPal\RestGateway or Omnipay\PayPal\ExpressGateway. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

157
        $response = $gateway->/** @scrutinizer ignore-call */ completePurchase(
Loading history...
158
            [
159
                'amount' => $amount,
160
                'currency' => 'USD',
161
                'description' => $userId,
162
                'payerId' => $request->input('PayerID'),
163
                'transactionReference' => $request->input('paymentId'),
164
            ])->send();
165
166
        if ($response->isSuccessful()) {
167
            $check = PaypalPayment::query()->where('transaction_id', $request->input('paymentId'))->first();
168
            if ($check === null) {
169
                User::updateUserRole($userId, $role->id);
170
                User::updateUserRoleChangeDate($userId, null, $role->addyears);
0 ignored issues
show
Bug introduced by
The property addyears does not seem to exist on Spatie\Permission\Models\Role. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
171
                PaypalPayment::query()->insert(['users_id' => $userId, 'transaction_id' => $request->input('paymentId'), 'created_at' => now(), 'updated_at' => now()]);
172
                $title = 'Cheers!';
173
                $meta_title = Settings::settingValue('site.main.title').' - Payment Complete';
174
                $meta_description = 'Payment Complete';
175
                $content = $this->smarty->fetch('thankyou.tpl');
176
                $this->smarty->assign(compact('content', 'meta_title', 'title', 'meta_description'));
177
178
                $this->pagerender();
179
            } else {
180
                echo 'Transaction already exists!';
181
            }
182
        } else {
183
            return redirect('payment_failed');
184
        }
185
    }
186
187
    public function paypalFailed()
188
    {
189
        echo 'Shit happens';
190
    }
191
}
192