CommissionJunction::_apiCall()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.6666
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Padosoft\AffiliateNetwork\Networks;
4
5
use Padosoft\AffiliateNetwork\Transaction;
6
use Padosoft\AffiliateNetwork\Merchant;
7
use Padosoft\AffiliateNetwork\Stat;
8
use Padosoft\AffiliateNetwork\Deal;
9
use Padosoft\AffiliateNetwork\AbstractNetwork;
10
use Padosoft\AffiliateNetwork\NetworkInterface;
11
use Padosoft\AffiliateNetwork\DealsResultset;
12
use Padosoft\AffiliateNetwork\ProductsResultset;
13
14
// require "../vendor/fubralimited/php-oara/Oara/Network/Publisher/CommissionJunction/Zapi/ApiClient.php";
15
16
/**
17
 * Class CommissionJunction
18
 * @package Padosoft\AffiliateNetwork\Networks
19
 */
20
class CommissionJunction extends AbstractNetwork implements NetworkInterface
21
{
22
    /**
23
     * @var object
24
     */
25
    private $_network = null;
26
    // private $_apiClient = null;
27
    private $_username = '';
28
    private $_password = '';
29
    private $_passwordApi = '';
30
    private $_publisher_id = '';
31
    protected $_tracking_parameter = 'sid';
32
33
    /**
34
     * @method __construct
35
     */
36 View Code Duplication
    public function __construct(string $username, string $passwordApi, $idSite)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
37
    {
38
        $this->_network = new \Oara\Network\Publisher\CommissionJunctionGraphQL();
39
        $this->_username = $username;
40
        $this->_password = $passwordApi;
41
        $this->_passwordApi = $passwordApi;
42
        $this->_publisher_id = $idSite;
43
44
        if (trim($idSite) != '') {
45
            $this->addAllowedSite($idSite);
46
        }
47
48
        $this->login($this->_username, $this->_password, $this->_publisher_id);
49
    }
50
51
    /**
52
     * @return bool
53
     */
54
    public function login(string $username, string $password, $idSite): bool
55
    {
56
        $this->_logged = false;
0 ignored issues
show
Bug introduced by
The property _logged does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
57
        if (isNullOrEmpty($username) && isNullOrEmpty($password)) {
58
            return false;
59
        }
60
        $this->_username = $username;
61
        $this->_password = $password;
62
        $this->_passwordApi = $password;
63
        $this->_publisher_id = $idSite;
64
        $credentials = array();
65
        $credentials["user"] = $this->_username;
66
        $credentials["password"] = $this->_username;
67
        $credentials["apipassword"] = $this->_passwordApi;
68
        $credentials["id_site"] = $idSite;
69
70
        if (trim($idSite) != '') {
71
            $this->addAllowedSite($idSite);
72
        }
73
74
        $this->_network->login($credentials);
75
        if ($this->_network->checkConnection()) {
76
            $this->_logged = true;
77
        }
78
79
        return $this->_logged;
80
    }
81
82
    /**
83
     * @return bool
84
     */
85
    public function checkLogin(): bool
86
    {
87
        return $this->_logged;
88
    }
89
90
    /**
91
     * @return array of Merchants
92
     */
93
    public function getMerchants(): array
94
    {
95
        $arrResult = array();
96
        $merchantList = $this->_network->getMerchantList();
97
        foreach ($merchantList as $merchant) {
98
            if ($merchant['status'] == 'Setup') {
99
                // Ignore setup programs not yet active
100
                continue;
101
            }
102
            $Merchant = Merchant::createInstance();
103
            $Merchant->merchant_ID = $merchant['cid'];
104
            $Merchant->name = $merchant['name'];
105
            // Added more info - 2018-04-23 <PN>
106
            $Merchant->url = $merchant['url'];
107
            if ($merchant['status'] == 'Active') {
108
                $Merchant->status = $merchant['relationship_status'];
109
            } else {
110
                $Merchant->status = $merchant['status'];
111
            }
112
            $arrResult[] = $Merchant;
113
        }
114
115
        return $arrResult;
116
    }
117
118
    /**
119
     * @param null | int $merchantID
120
     * @param int $page
121
     * @param int $records_per_page
122
     * @return DealsResultset array of Deal
123
     * https://developers.cj.com/docs/rest-apis/link-search
124
     */
125
    public function getDeals($merchantID = NULL, int $page = 1, int $records_per_page = 100): DealsResultset
126
    {
127
        if (empty($page)) {
128
            $page = 1;
129
        }
130
        if (empty($records_per_page)) {
131
            $records_per_page = 100;
132
        }
133
        if (empty($merchantID)) {
134
            $merchantID = 'joined';
135
        }
136
        $arrResult = new DealsResultset();
137
        $arrResult->items = $records_per_page;
138
139
        while ((int)$arrResult->items >= (int)$records_per_page) {
140
141
            try {
142
                //<JC> 2017-10-23  (valid keys are: advertiser-ids, category, event-name, keywords, language, link-type, page-number, promotion-end-date, promotion-start-date, promotion-type, records-per-page, website-id)
143
                $response = $this->_apiCall(
144
                    'https://link-search.api.cj.com/v2/link-search?website-id=' . $_ENV['CJ_API_WEBSITE_ID'] .
145
                    '&advertiser-ids=' . $merchantID .
146
                    '&records-per-page=' . $records_per_page .
147
                    '&page-number=' . $page .
148
                    '&promotion-type=coupon'
149
                );
150
151
                if ($response === false || \preg_match("/<error-message>/", $response)) {
152
                    preg_match('/<error-message>(.*)<\/error-message>/', $response, $matches);
153
                    $error_msg = $matches[1] ?? $response;
154
                    echo "[CommissionJunction][Error] " . $error_msg . PHP_EOL;
155
                    var_dump($error_msg);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($error_msg); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
156
                    throw new \Exception($error_msg);
157
                }
158
159
                $arrResponse = xml2array($response);
160
161
                if (!is_array($arrResponse) || count($arrResponse) <= 0) {
162
                    return $arrResult;
163
                }
164
                if (!isset($arrResponse['cj-api']['links'])) {
165
                    return $arrResult;
166
                }
167
                if (!isset($arrResponse['cj-api']['links']['link'])) {
168
                    return $arrResult;
169
                }
170
                $arrResult->page = $arrResponse['cj-api']['links_attr']['page-number'];
171
                $arrResult->items = $arrResponse['cj-api']['links_attr']['records-returned'];
172
                $arrResult->total = $arrResponse['cj-api']['links_attr']['total-matched'];
173
                ($arrResult->total > 0) ? $arrResult->num_pages = (int)ceil($arrResult->total / $records_per_page) : $arrResult->num_pages = 0;
0 ignored issues
show
Bug introduced by
The property num_pages does not seem to exist in Padosoft\AffiliateNetwork\DealsResultset.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
174
175
                $a_links = $arrResponse['cj-api']['links']['link'];
176
                foreach ($a_links as $link) {
177
                    if (!isset($link['link-id'])) {
178
                        continue;
179
                    }
180
                    $Deal = Deal::createInstance();
181
                    $Deal->deal_ID = $link['link-id'];
182
                    $Deal->name = $link['link-name'];
183
                    $Deal->language = $link['language'];
184
                    $Deal->description = $link['description'];
185
                    $Deal->note = $link['description'];
0 ignored issues
show
Bug introduced by
The property note does not seem to exist in Padosoft\AffiliateNetwork\Deal.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
186
                    $Deal->merchant_ID = $link['advertiser-id'];
187
                    $Deal->merchant_name = $link['advertiser-name'];
188
                    $Deal->default_track_uri = $link['clickUrl'];
189
                    $Deal->description = $link['description'];
190
                    $Deal->title = $link['link-name'];
0 ignored issues
show
Bug introduced by
The property title does not seem to exist in Padosoft\AffiliateNetwork\Deal.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
191
                    if (!empty($link['promotion-start-date'])) {
192
                        $startDate = new \DateTime($link['promotion-start-date']);
193
                        $Deal->start_date = $startDate;
194
                    }
195
                    if (!empty($link['promotion-end-date'])) {
196
                        $endDate = new \DateTime($link['promotion-end-date']);
197
                        $Deal->end_date = $endDate;
198
                    }
199
                    $Deal->code = $link['coupon-code'];
200
                    $Deal->deal_type = \Oara\Utilities::OFFER_TYPE_VOUCHER;
201
                    $arrResult->deals[0][] = $Deal;
202
                }
203
                $page++;
204
            } catch (\Exception $e) {
205
                echo "[CommissionJunction][Error] " . $e->getMessage() . PHP_EOL;
206
                var_dump($e->getTraceAsString());
207
                throw new \Exception($e);
208
            }
209
        }
210
211
        return $arrResult;
212
    }
213
214
    /**
215
     * @param \DateTime $dateFrom
216
     * @param \DateTime $dateTo
217
     * @param int $merchantID
0 ignored issues
show
Documentation introduced by
There is no parameter named $merchantID. Did you maybe mean $arrMerchantID?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
218
     * @return array of Transaction
219
     */
220
    public function getSales(\DateTime $dateFrom, \DateTime $dateTo, array $arrMerchantID = array()): array
221
    {
222
        $arrResult = array();
223
        // User passed $arrMerchantID, don't fill it with active merchants only - 2017-10-12 <PN>
224
        /*
225
        if (count( $arrMerchantID ) < 1) {
226
            $merchants = $this->getMerchants();
227
            foreach ($merchants as $merchant) {
228
                $arrMerchantID[$merchant->merchant_ID] = ['cid' => $merchant->merchant_ID, 'name' => $merchant->name];
229
            }
230
        }
231
        */
232
        $transactionList = $this->_network->getTransactionList($arrMerchantID, $dateFrom, $dateTo);
233
        //echo "<br>merchants id array<br>".print_r($arrMerchantID);
234
        //$counter=0;
235
        foreach ($transactionList as $transaction) {
236
            $Transaction = Transaction::createInstance();
237
            $Transaction->status = $transaction['status'];
238
            $Transaction->amount = $transaction['amount'];
239
            $Transaction->custom_ID = $transaction['custom_id'];
240
            $Transaction->unique_ID = $transaction['unique_id'];
241
            // Use 'original-action-id' instead of 'order-id' as reference field between original commission and adjust/correction commission - 2018-07-13 <PN>
242
            // $Transaction->transaction_ID = $transaction['order-id'];
243
            $Transaction->transaction_ID = $transaction['original-action-id'];
244
            $Transaction->commission = $transaction['commission'];
245
            if (!empty($transaction['date'])) {
246
                $date = new \DateTime($transaction['date']);
247
                $Transaction->date = $date; // $date->format('Y-m-d H:i:s');
0 ignored issues
show
Documentation Bug introduced by
It seems like $date of type object<DateTime> is incompatible with the declared type string of property $date.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
248
            }
249
            $Transaction->merchant_ID = $transaction['merchantId'];
250
            $Transaction->original = $transaction['original'];
251
            //original	Displays either a '1' indicating an original transaction or a '0' indicating a non-original or correction transaction.
252
            // considero transazioni valide solo quelle di tipo original come viene fatto dal report consultabile sul sito web di c.j.
253
            // Don't check for 'original' to get DECLINED transactions - 2017-12-13 <PN>
254
            // if ($transaction['original'] == 'true') {
255
            $arrResult[] = $Transaction;
256
            // }
257
            /*
258
            echo "custom_id ".$transaction['custom_id']." unique_id ".$transaction['unique_id']." aid ".$transaction['aid']." commission-id ".$transaction['commission-id'].
259
            " order-id ".$transaction['order-id']." original ".$transaction['original']."<br>";
260
            */
261
262
        }
263
        //echo "<br>num transazioni: ".$counter;
264
        return $arrResult;
265
    }
266
267
    /**
268
     * @param \DateTime $dateFrom
269
     * @param \DateTime $dateTo
270
     * @param int $merchantID
271
     * @return array of Stat
272
     */
273
    public function getStats(\DateTime $dateFrom, \DateTime $dateTo, int $merchantID = 0): array
274
    {
275
        return array();
276
        /*
277
        $this->_apiClient->setConnectId($this->_username);
278
        $this->_apiClient->setSecretKey($this->_password);
279
        $dateFromIsoEngFormat = $dateFrom->format('Y-m-d');
280
        $dateToIsoEngFormat = $dateTo->format('Y-m-d');
281
        $response = $this->_apiClient->getReportBasic($dateFromIsoEngFormat, $dateToIsoEngFormat);
282
        $arrResponse = json_decode($response, true);
283
        $reportItems = $arrResponse['reportItems'];
284
        $Stat = Stat::createInstance();
285
        $Stat->reportItems = $reportItems;
286
287
        return array($Stat);
288
        */
289
    }
290
291
    /**
292
     * @param array $params
293
     *
294
     * @return ProductsResultset
295
     */
296
    public function getProducts(array $params = []): ProductsResultset
297
    {
298
        // TODO: Implement getProducts() method.
299
        throw new \Exception("Not implemented yet");
300
    }
301
302
    /**
303
     * Api call CommissionJunction
304
     */
305
    private function _apiCall($url)
306
    {
307
        $ch = curl_init();
308
        curl_setopt($ch, CURLOPT_URL, $url);
309
        curl_setopt($ch, CURLOPT_POST, FALSE);
310
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
311
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
312
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
313
        if (!empty($this->_publisher_id)) {
314
            curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer " . $this->_passwordApi));
315
        } else {
316
            curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: " . $this->_passwordApi));
317
        }
318
319
        $curl_results = curl_exec($ch);
320
        curl_close($ch);
321
        return $curl_results;
322
    }
323
324
325
    public function getTrackingParameter()
326
    {
327
        return $this->_tracking_parameter;
328
    }
329
330
    public function addAllowedSite($idSite)
331
    {
332
        if (trim($idSite) != '') {
333
            $this->_network->addAllowedSite($idSite);
334
        }
335
    }
336
337
}
338