Completed
Pull Request — master (#14)
by Christian
10:33
created

MWSClient::getTimeStamp()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Looxis\LaravelAmazonMWS;
4
5
use GuzzleHttp\Client;
6
use Looxis\LaravelAmazonMWS\Exceptions\CountryIsMissingException;
7
use Looxis\LaravelAmazonMWS\Exceptions\CountryNotAvailableException;
8
9
class MWSClient
10
{
11
    const SIGNATURE_METHOD = 'HmacSHA256';
12
    const SIGNATURE_VERSION = '2';
13
    const DATE_FORMAT = "Y-m-d\TH:i:s.\\0\\0\\0\\Z";
14
    const APPLICATION_NAME = 'Looxis/MwsClient';
15
    const APPLICATION_VERSION = '0.0.1';
16
17
    protected $accessKeyId;
18
    protected $secretKey;
19
    protected $sellerId;
20
    protected $client;
21
    protected $marketPlaces;
22
    protected $mwsAuthToken;
23
24
    protected $marketplaceIds = [
25
        'A2Q3Y263D00KWC' => 'mws.amazonservices.com',
26
        'A2EUQ1WTGCTBG2' => 'mws.amazonservices.ca',
27
        'A1AM78C64UM0Y8' => 'mws.amazonservices.com.mx',
28
        'ATVPDKIKX0DER' => 'mws.amazonservices.com',
29
        'A2VIGQ35RCS4UG' => 'mws.amazonservices.ae',
30
        'A1PA6795UKMFR9' => 'mws-eu.amazonservices.com',
31
        'ARBP9OOSHTCHU' => 'mws-eu.amazonservices.com',
32
        'A1RKKUPIHCS9HS' => 'mws-eu.amazonservices.com',
33
        'A13V1IB3VIYZZH' => 'mws-eu.amazonservices.com',
34
        'A1F83G8C2ARO7P' => 'mws-eu.amazonservices.com',
35
        'A21TJRUUN4KGV' => 'mws.amazonservices.in',
36
        'APJ6JRA9NG5V4' => 'mws-eu.amazonservices.com',
37
        'A17E79C6D8DWNP' => 'mws-eu.amazonservices.com',
38
        'A33AVAJ2PDY3EV' => 'mws-eu.amazonservices.com',
39
        'A19VAU5U5O7RUS' => 'mws-fe.amazonservices.com',
40
        'A39IBJ37TRP1C6' => 'mws.amazonservices.com.au',
41
        'A1VC38T7YXB528' => 'mws.amazonservices.jp',
42
        'A1805IZSGTT6HS' => 'mws-eu.amazonservices.com',
43
    ];
44
45
    protected $countries = [
46
        'BR' => 'A2Q3Y263D00KWC',
47
        'CA' => 'A2EUQ1WTGCTBG2',
48
        'MX' => 'A1AM78C64UM0Y8',
49
        'US' => 'ATVPDKIKX0DER',
50
        'AE' => 'A2VIGQ35RCS4UG',
51
        'DE' => 'A1PA6795UKMFR9',
52
        'EG' => 'ARBP9OOSHTCHU',
53
        'ES' => 'A1RKKUPIHCS9HS',
54
        'FR' => 'A13V1IB3VIYZZH',
55
        'GB' => 'A1F83G8C2ARO7P',
56
        'IN' => 'A21TJRUUN4KGV',
57
        'IT' => 'APJ6JRA9NG5V4',
58
        'SA' => 'A17E79C6D8DWNP',
59
        'TR' => 'A33AVAJ2PDY3EV',
60
        'SG' => 'A19VAU5U5O7RUS',
61
        'AU' => 'A39IBJ37TRP1C6',
62
        'JP' => 'A1VC38T7YXB528',
63
        'NL' => 'A1805IZSGTT6HS',
64
    ];
65
66
    public function __construct(Client $client = null)
67
    {
68
        $this->accessKeyId = config('amazon-mws.access_key_id');
69
        $this->secretKey = config('amazon-mws.secret_key');
70
        $this->sellerId = config('amazon-mws.seller_id');
71
        $this->mwsAuthToken = config('amazon-mws.mws_auth_token');
72
        $this->marketPlaces = ['DE'];
73
        $this->client = $client ?: new Client(['timeout'  => 60]);
74
    }
75
76
    public function setMarketPlaces($countryCodes)
77
    {
78
        $countryCodes = is_array($countryCodes) ? $countryCodes : func_get_args();
79
        $this->marketPlaces = $countryCodes;
80
    }
81
82
    public function getCurrentMarketPlaces()
83
    {
84
        return $this->marketPlaces;
85
    }
86
87
    public function getTimeStamp()
88
    {
89
        return gmdate(self::DATE_FORMAT, time());
90
    }
91
92
    public function getAccessKeyId()
93
    {
94
        return $this->accessKeyId;
95
    }
96
97
    public function setAccessKeyId($key)
98
    {
99
        $this->accessKeyId = $key;
100
101
        return $this;
102
    }
103
104
    public function getSellerId()
105
    {
106
        return $this->sellerId;
107
    }
108
109
    public function setSellerId($id)
110
    {
111
        $this->sellerId = $id;
112
113
        return $this;
114
    }
115
116
    public function getMWSAuthToken()
117
    {
118
        return $this->mwsAuthToken;
119
    }
120
121
    public function getSignatureMethod()
122
    {
123
        return self::SIGNATURE_METHOD;
124
    }
125
126
    public function getSignatureVersion()
127
    {
128
        return self::SIGNATURE_VERSION;
129
    }
130
131
    public function getDomain()
132
    {
133
        $mainMarketPlace = $this->marketPlaces[0];
134
        if ($mainMarketPlace) {
135
            $marketPlaceId = $this->countries[$mainMarketPlace];
136
137
            return $this->marketplaceIds[$marketPlaceId];
138
        }
139
140
        throw new CountryIsMissingException();
141
    }
142
143
    public function getCountry()
144
    {
145
        return $this->country;
0 ignored issues
show
Bug introduced by
The property country 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...
146
    }
147
148
    public function setCountry($country)
149
    {
150
        if (in_array($country, array_keys($this->countries))) {
151
            $this->country = $country;
152
153
            return $this;
154
        } else {
155
            throw new CountryNotAvailableException();
156
        }
157
    }
158
159
    public function getMarketPlaceIds()
160
    {
161
        return $this->marketplaceIds;
162
    }
163
164
    public function post($action, $path, $version, $params = [], $body = null)
165
    {
166
        $headers = [
167
            'Accept' => 'application/xml',
168
            'x-amazon-user-agent' => self::APPLICATION_NAME.'/'.self::APPLICATION_VERSION,
169
        ];
170
171
        if ($action === 'SubmitFeed') {
172
            $headers['Content-Type'] = 'text/xml; charset=iso-8859-1';
173
        }
174
175
        $requestOptions = [
176
            'headers' => $headers,
177
            'body' => $body,
178
            'query' => $this->getQuery($path, $action, $version, $params),
179
        ];
180
181
        $uri = 'https://'.$this->getDomain().$path;
182
        $response = $this->client->post($uri, $requestOptions);
183
        $xmlResponse = simplexml_load_string($response->getBody()->getContents());
184
        $json = json_encode($xmlResponse);
185
186
        return json_decode($json, true);
187
    }
188
189
    public function getDefaultQueryParams($action, $version, $params = [])
190
    {
191
        $queryParameters = [
192
            'Action' => $action,
193
            'Timestamp' => $this->getTimeStamp(),
194
            'AWSAccessKeyId' => $this->getAccessKeyId(),
195
            'SellerId' => $this->getSellerId(),
196
            'MWSAuthToken' => $this->getMWSAuthToken(),
197
            'SignatureMethod' => $this->getSignatureMethod(),
198
            'SignatureVersion' => $this->getSignatureVersion(),
199
            'Version' => $version,
200
        ];
201
        $queryParameters = array_merge($queryParameters, $this->getMarketPlaceParams());
202
        $queryParameters = array_merge($queryParameters, $params);
203
        ksort($queryParameters);
204
205
        return $queryParameters;
206
    }
207
208
    public function getMarketPlaceParams()
209
    {
210
        $params = [];
211
        foreach ($this->marketPlaces as $index => $marketPlace) {
212
            $keyName = 'MarketplaceId.Id.'.($index + 1);
213
            $params[$keyName] = $this->countries[$marketPlace];
214
        }
215
216
        return $params;
217
    }
218
219
    public function generateRequestUri($action, $version, $params = [])
220
    {
221
        return http_build_query($this->getDefaultQueryParams($action, $version, $params), null, '&', PHP_QUERY_RFC3986);
222
    }
223
224
    public function getQueryStringForSignature($path, $action, $version, $params = [])
225
    {
226
        return  'POST'
227
                    ."\n"
228
                    .$this->getDomain()
229
                    ."\n"
230
                    .$path
231
                    ."\n"
232
                    .$this->generateRequestUri($action, $version, $params);
233
    }
234
235
    public function generateSignature($path, $action, $version, $params = [])
236
    {
237
        $signature = base64_encode(
238
            hash_hmac(
239
                'sha256',
240
                $this->getQueryStringForSignature($path, $action, $version, $params),
241
                $this->secretKey,
242
                true
243
            )
244
        );
245
246
        return $signature;
247
    }
248
249
    public function getQuery($path, $action, $version, $params = [])
250
    {
251
        $queryParameters = $this->getDefaultQueryParams($action, $version, $params);
252
        $queryParameters['Signature'] = $this->generateSignature($path, $action, $version, $params);
253
254
        return $queryParameters;
255
    }
256
}
257