· 6 years ago · Oct 20, 2018, 11:42 AM
1<?php
2/**
3 * Example of retrieving the products list using Admin account via Magento REST API. OAuth authorization is used
4 * Preconditions:
5 * 1. Install php oauth extension
6 * 2. If you were authorized as a Customer before this step, clear browser cookies for 'yourhost'
7 * 3. Create at least one product in Magento
8 * 4. Configure resource permissions for Admin REST user for retrieving all product data for Admin
9 * 5. Create a Consumer
10 */
11// $callbackUrl is a path to your file with OAuth authentication example for the Admin user
12$callbackUrl = "http://yourhost/oauth_admin.php";
13$temporaryCredentialsRequestUrl = "http://yourhost/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
14$adminAuthorizationUrl = 'http://yourhost/admin/oAuth_authorize';
15$accessTokenRequestUrl = 'http://yourhost/oauth/token';
16$apiUrl = 'http://yourhost/api/rest';
17$consumerKey = 'yourconsumerkey';
18$consumerSecret = 'yourconsumersecret';
19
20session_start();
21if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {
22 $_SESSION['state'] = 0;
23}
24try {
25 $authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
26 $oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
27 $oauthClient->enableDebug();
28
29 if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
30 $requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
31 $_SESSION['secret'] = $requestToken['oauth_token_secret'];
32 $_SESSION['state'] = 1;
33 header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
34 exit;
35 } else if ($_SESSION['state'] == 1) {
36 $oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
37 $accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
38 $_SESSION['state'] = 2;
39 $_SESSION['token'] = $accessToken['oauth_token'];
40 $_SESSION['secret'] = $accessToken['oauth_token_secret'];
41 header('Location: ' . $callbackUrl);
42 exit;
43 } else {
44 $oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
45
46 $resourceUrl = "$apiUrl/products";
47 $oauthClient->fetch($resourceUrl, array(), 'GET', array('Content-Type' => 'application/json'));
48 $productsList = json_decode($oauthClient->getLastResponse());
49 print_r($productsList);
50 }
51} catch (OAuthException $e) {
52 print_r($e->getMessage());
53 echo "<br/>";
54 print_r($e->lastResponse);
55}