Passed
Pull Request — master (#90)
by mohammad
02:41
created

Digipay::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 6
rs 10
1
<?php
2
3
4
namespace Shetabit\Multipay\Drivers\Digipay;
5
6
use GuzzleHttp\Client;
7
use Shetabit\Multipay\Abstracts\Driver;
8
use Shetabit\Multipay\Contracts\ReceiptInterface;
9
use Shetabit\Multipay\Exceptions\InvalidPaymentException;
10
use Shetabit\Multipay\Exceptions\PurchaseFailedException;
11
use Shetabit\Multipay\Invoice;
12
use Shetabit\Multipay\Receipt;
13
use Shetabit\Multipay\RedirectionForm;
14
use Shetabit\Multipay\Request;
15
16
class Digipay extends Driver
17
{
18
    /**
19
    * Digipay Client.
20
    *
21
    * @var object
22
    */
23
    protected $client;
24
25
    /**
26
     * Invoice
27
     *
28
     * @var Invoice
29
     */
30
    protected $invoice;
31
32
    /**
33
     * Driver settings
34
     *
35
     * @var object
36
     */
37
    protected $settings;
38
    /**
39
     * Digipay Oauth Token
40
     *
41
     * @var string
42
     */
43
    protected $oauthToken;
44
45
    /**
46
     * Digipay constructor.
47
     * Construct the class with the relevant settings.
48
     *
49
     * @param Invoice $invoice
50
     * @param $settings
51
     */
52
    public function __construct(Invoice $invoice, $settings)
53
    {
54
        $this->invoice($invoice);
55
        $this->settings=$settings;
56
        $this->client = new Client();
57
        $this->oauthToken = $this->oauth();
58
    }
59
60
    public function purchase()
61
    {
62
        $details = $this->invoice->getDetails();
63
64
        $phone = null;
65
        if (!empty($details['phone'])) {
66
            $phone = $details['phone'];
67
        } elseif (!empty($details['mobile'])) {
68
            $phone = $details['mobile'];
69
        }
70
        $data = array(
71
            'amount' => $this->invoice->getAmount(),
72
            'phone' => $phone,
73
            'providerId' => $this->invoice->getUuid(),
74
            'redirectUrl' => $this->settings->callbackUrl,
75
            'type' => 0,
76
            'userType' => is_null($phone) ? 2 : 0
77
        );
78
79
        $response = $this
80
            ->client
81
            ->request(
82
                'POST',
83
                $this->settings->apiPurchaseUrl,
84
                [
85
                    "json" => $data,
86
                    "headers" => [
87
                        'Content-Type' => 'application/json',
88
                        'Authorization' => 'Bearer '.$this->oauthToken
89
                    ],
90
                    "http_errors" => false,
91
                ]
92
            );
93
94
        $body = json_decode($response->getBody()->getContents(), true);
95
        if ($response->getStatusCode() != 200) {
96
            // error has happened
97
            $message = $body['result']['message'] ?? 'خطا در هنگام درخواست برای پرداخت رخ داده است.';
98
            throw new PurchaseFailedException($message);
99
        }
100
101
        $this->invoice->transactionId($body['ticket']);
102
103
        // return the transaction's id
104
        return $this->invoice->getTransactionId();
105
    }
106
107
    public function pay(): RedirectionForm
108
    {
109
        $payUrl = $this->settings->apiPaymentUrl.$this->invoice->getTransactionId();
110
111
        return $this->redirectWithForm($payUrl, [], 'GET');
112
    }
113
114
    public function verify(): ReceiptInterface
115
    {
116
        $tracingId=Request::input("trackingCode");
117
118
        $response = $this->client->request(
119
            'POST',
120
            $this->settings->apiVerificationUrl.$tracingId,
121
            [
122
                'json' => [],
123
                "headers" => [
124
                    "Accept" => "application/json",
125
                    "Authorization" => "Bearer ".$this->oauthToken,
126
                ],
127
                "http_errors" => false,
128
            ]
129
        );
130
        $body = json_decode($response->getBody()->getContents(), true);
131
132
        if ($response->getStatusCode() != 200) {
133
            $message = 'تراکنش تایید نشد';
134
135
            throw new InvalidPaymentException($message);
136
        }
137
138
        return new Receipt('digipay', $body["trackingCode"]);
139
    }
140
141
    protected function oauth()
142
    {
143
        $response = $this
144
            ->client
145
            ->request(
146
                'POST',
147
                $this->settings->apiOauthUrl,
148
                [
149
                    "headers" => [
150
                        'Content-Type' => 'multipart/form-data',
151
                        'Authorization' => 'Basic '.base64_encode("{$this->settings->client_id}:{$this->settings->client_secret}")
152
                    ],
153
                    "username" => $this->settings->username,
154
                    "password" => $this->settings->password,
155
                    "grant_type" => 'password',
156
                ]
157
            );
158
        if ($response->getStatusCode()!=200) {
159
            if ($response->getStatusCode()==401) {
160
                throw new PurchaseFailedException("خطا نام کاربری یا رمز عبور شما اشتباه می باشد.");
161
            } else {
162
                throw new PurchaseFailedException("خطا در هنگام احراز هویت.");
163
            }
164
        }
165
        $body = json_decode($response->getBody()->getContents(), true);
166
        return $body['access_token'];
167
    }
168
}
169