如何在 Magento 1 使用 REST API
Magento有API的建置與使用方式,今天就要先來講Magento原生API的使用方式。
- 設定使用者 system > web services > REST – OAuth Consumers 新增API使用者(各設定值請依照你的實際需求設定)
- 請參考下方程式碼使用Rest API(請記得安裝 php-oauth插件)
另外,若你的Api Url一直是404:
– Ngnix 請檢查 rewrite /api/rest /api.php?type=rest
– Apache 請檢查 .htaccess RewriteRule ^api/rest api.php?type=rest [QSA,L]
<?php $callbackUrl = "http://fafa.magento.com/callback.php"; $temporaryCredentialsRequestUrl = "http://fafa.magento.com/oauth/initiate?oauth_callback=" . urlencode($callbackUrl); $adminAuthorizationUrl = 'http://fafa.magento.com/admin/oauth_authorize'; $accessTokenRequestUrl = 'http://fafa.magento.com/oauth/token'; $apiUrl = 'http://fafa.magento.com/api/rest'; $consumerKey = c661584e711420a7a74da19cfe69c7d2;//請輸入你的Key $consumerSecret = e2c05ec8959650205ea59fb21e86969b;//請輸入你的Secret session_start(); if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) { $_SESSION['state'] = 0; } try { $authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI; $oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType); $oauthClient->enableDebug(); if (!isset($_GET['oauth_token']) && !$_SESSION['state']) { // 第一步 獲得臨時token $requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl); $_SESSION['secret'] = $requestToken['oauth_token_secret']; $_SESSION['state'] = 1; // 導向驗證身分頁面 header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']); exit; } elseif ($_SESSION['state'] == 1) { //取得AccessToken $oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']); $accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl); $_SESSION['state'] = 2; $_SESSION['token'] = $accessToken['oauth_token']; $_SESSION['secret'] = $accessToken['oauth_token_secret']; header('Location: ' . $callbackUrl); exit; } else { // POST 增加產品請求到後端 $oauthClient->setToken($_SESSION['token'], $_SESSION['secret']); $resourceUrl = "$apiUrl/products"; $productData = json_encode(array( 'type_id' => 'simple', 'attribute_set_id' => 4, 'sku' => 'simple' . uniqid(), 'weight' => 1, 'status' => 1, 'visibility' => 4, 'name' => 'Simple Product', 'description' => 'Simple Description', 'short_description' => 'Simple Short Description', 'price' => 99.95, 'tax_class_id' => 0, )); $headers = array('Content-Type' => 'application/json'); $oauthClient->fetch($resourceUrl, $productData, OAUTH_HTTP_METHOD_POST, $headers); print_r($oauthClient->getLastResponseInfo()); } } catch (OAuthException $e) { print_r($e); }
以上就是Magento 1原生API的使用介紹,當然如果你有其他的商業需求,我們都可以開發客製化API來滿足你,歡迎聯絡我們來進一步討論。
我要留言