創建自用源碼庫
您可以創建自己的源碼庫來連接新蛋商城的API 系統。您的代碼須用新蛋商城建議的格式來創建並標記請求,這樣您也可以順利解析XML格式的回覆。您可以通過下列步驟來連接新蛋商城的API 系統:
步驟1- 使用正確的新蛋商城的API URL
步驟2- 在請求URL中指定正確的參數值
步驟3- 指定正確的HTTP請求方式以及可接受的XML/Json內容類別型
步驟4- 在請求中附上正確的API Key 和Secret Key(參考上面的認證例子)
步驟5- 按照規定創建請求內容,然後提交HTTP請求
步驟6- 正確解析回覆
請求格式
新蛋商城API 系統支援通過調用Restful服務操作來處理查詢/更新的請求。查詢請求是簡單的HTTP請求, 分別使用URL或者HTTP主體中帶有查詢參數的GET或者POST方法來實現。而更新請求則是分別使用URL或者HTTP主體中帶有更新參數的PUT或者DELETE方法來實現。
為了防止協力廠商竊取您與新蛋的通訊資訊,新蛋商城API要求使用安全超文字傳輸協定HTTPS。
創建HTTP請求
為了創建新蛋商城查詢/更新的API 請求,您首先需要創建一個格式正確的請求URL。您可以參考您想要使用的API 服務的URL範本(請參照API參考部分)。
下表列出的是在您HTTP請求中可能會使用的值。
| 名稱 | 是否必填? | 描述 |
| Request URL | 是 | 您正在使用的新蛋商城API服務端點 |
| Request Method | 是 | API服務所要求的GET/POST或者PUT/DELETE方法 |
| Body Content-type | 否 | 在請求文件主體中內容為XML/Json格式,預設為XML格式 |
| Response Content-type | 否 | 回應內容為XML/Json格式,預設為XML格式 |
| Authentication header | 是 | 格式:Anthorization:{api-key}
經授權的API服務商提供的API key |
| SecretKey header | 是 | 格式:Secretkey:{secretkey}
經授權的API服務商提供的金鑰 |
| RAW body | 否 | 通過請求文件主體傳遞參數。內容格式應該符合API服務的規範 |
註:API參考部分對於每個API功能都包含了重要內容供您參考
例如:
GET Https://api.newegg.com/marketplace/ordermgmt/orderstatus/orders/{ordernumber}?sellerid={sellerid}
Authorization: 720ddc067f4d115bd544aff46bc75634
SecretKey: 21EC2020-3AEA-1069-A2DD-08002B30309D
Content-Type: application/xml
Accept: application/xml
HTTP方法 – 指定使用的請求方法
認證 – 表明這個服務需要認證才能使用
請求格式 – 在請求主體中請求參數採用的格式
回應格式 – 回應內容所支援的格式
頻率限制 – API請求限制
請求參數:
URL參數 – 請求URL中的必填參數
請求參數 – 一些在請求主體中指定的參數。格式必須是XML或者Json;您可以從上面的相關請求資訊裡的“請求格式”中獲取可支援的類型。
註:請確保您的請求URL全都是小寫(除Seller ID)並且不能包含任何空格或者分行符號。
錯誤請求
如果您使用以下類型提交了一個不合理的請求,新蛋商城API會返回一個錯誤請求提示(HTTP 狀態碼:400)
- 非法請求主體。例如格式不正確的XML,不正確的標記或者是資料類型
示例:XML, Response
<?xml version="1.0" encoding="utf-8"?>
<Errors>
<Error>
<Code>CE003</Code>
<Message>XML parsing error. The 'NeweggAPIRequest1' start tag on line 1 position 2 does not match the end tag of 'NeweggAPIRequest'. Line 1, position 451.</Message>
</Error>
</Errors>
示例:Json, Response
[
{
"Code": "CE003",
"Message": "XML parsing error. The 'NeweggAPIRequest1' start tag on line 1 position 2 does not match the end tag of 'NeweggAPIRequest'. Line 1, position 451."
}
]
- 業務驗證失敗。無效的資料請求或者與業務需求不匹配。有關詳細的錯誤代碼和資訊,請參考每章節後的“請求失敗錯誤資訊”部分。
示例:XML, Response
<?xml version="1.0" encoding="utf-8" ?>
<Errors>
<Error>
<Code>SO011</Code>
<Message>Only unshipped orders can be shipped. The order status is currently Closed</Message>
</Error>
</Errors>
示例:Json, Response
[
{
"Code": "SO011",
"Message": "Only unshipped orders can be shipped. The order status is currently Closed"
}
]
為了能在您自己的程式上正確的解析錯誤資訊,請參考“示例代碼”部分的“錯誤請求的異常處理”模組。
代碼示例
請註,這些示例只是示範如何使用新蛋商城API功能和資源。並不包含比如每種程式設計語言所需要的驗證/安全等額外需求。
C#代碼示例
下述代碼示範了如何使用.NET和C#語言對賣家 A006 的新蛋商品 9SIA00600000023 進行庫存數量的查詢。
- 創建一個類(Class)來對API回覆進行反序列化(De-serialize)
示例:C#,Inventory response entity(庫存回覆)
public class InventoryResult
{
public string SellerID { get; set; }
public string ItemNumber { get; set; }
public int AvailableQuantity { get; set; }
public string Active { get; set; }
public string SellerPartNumber { get; set; }
public string ShipByNewegg { get; set; }
}
- 獲取有效庫存數量
示例:C#,Get Item Inventory(獲取現有商品庫存)
Console.WriteLine(string.Format("Newegg Marketplace API - Get Inventory request at:{0}", DateTime.Now.ToString()));
Console.WriteLine("");
Console.WriteLine("*********************************************************************");
Console.WriteLine("");
try
{
InventoryResult inventoryResult = null;
//Determine the correct Newegg Marketplace API endpoint to use.
// Please make sure your request URL is all in lower case
string endpoint = @"https://api.newegg.com/marketplace/contentmgmt/item/inventory?sellerid={0}";
endpoint = String.Format(endpoint, "A006");
//Create an HttpWebRequest
System.Net.HttpWebRequest request =
System.Net.WebRequest.Create(endpoint) as HttpWebRequest;
//Remove proxy
request.Proxy = null;
//Specify the request method
request.Method = "POST";
//Specify the xml/Json request and response content types.
request.ContentType = "application/xml";
request.Accept = "application/xml";
//Attach authorization information
request.Headers.Add("Authorization", "your API-key here");
request.Headers.Add("Secretkey", "your secretkey here");
//Construct the query criteria in the request body
string requestBody = @"
<ContentQueryCriteria>
<Type>1</Type>
<Value>A006ZX-35833</Value>
</ContentQueryCriteria>";
byte[] byteStr = Encoding.UTF8.GetBytes(requestBody);
request.ContentLength = byteStr.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(byteStr, 0, byteStr.Length);
}
//Parse the response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine(String.Format("Code:{0}.Error:{1}",
response.StatusCode.ToString(), response.StatusDescription));
return;
}
using (Stream responseStream = response.GetResponseStream())
{
XmlSerializer serializer =
new XmlSerializer(typeof(InventoryResult));
inventoryResult =
serializer.Deserialize(responseStream) as InventoryResult;
}
}
string sellerID = inventoryResult.SellerID;
string itemNumber = inventoryResult.ItemNumber;
int availableQuantity = inventoryResult.AvailableQuantity;
string message = String.Format("SellerID:{0} ItemNumber:{1} Availble Quantity:{2} \r\n Active:{3} SellerPartNumber:{4} ShipByNewegg:{5}",
inventoryResult.SellerID,
inventoryResult.ItemNumber,
inventoryResult.AvailableQuantity,
inventoryResult.Active,
inventoryResult.SellerPartNumber,
inventoryResult.ShipByNewegg);
Console.WriteLine(message);
}
catch (WebException we)//Error Handling for Bad Request
{
if (((WebException)we).Status == WebExceptionStatus.ProtocolError)
{
WebResponse errResp = ((WebException)we).Response;
using (Stream respStream = errResp.GetResponseStream())
{
StreamReader reader = new StreamReader(respStream);
Console.WriteLine(String.Format("{0}", reader.ReadToEnd()));
}
}
}
catch (Exception ex)//unhandle error
{
Console.WriteLine(string.Format("exception: at time:{0}", DateTime.Now.ToString()));
Console.WriteLine(ex.Message + "---->");
Console.WriteLine(ex.StackTrace.ToString());
}
Console.WriteLine("");
Console.WriteLine("*********************************************************************");
Console.WriteLine("");
Console.WriteLine("Please input any key to exit……");
Console.ReadLine();
錯誤請求的異常處理(狀態碼=400)
try
{
//Your code here
}
catch (WebException we)//Error Handling for Bad Request
{
if (((WebException)we).Status == WebExceptionStatus.ProtocolError)
{
WebResponse errResp = ((WebException)we).Response;
using (Stream respStream = errResp.GetResponseStream())
{
StreamReader reader = new StreamReader(respStream);
Console.WriteLine(String.Format("{0}", reader.ReadToEnd()));
}
}
}
Java示例
下述代碼示範了如何通過Java來檢索新蛋商城API系統中的訂單資訊。
/*
* To change this template, choose Tools | Templates
* And open the template in the editor.
*/
package marketplaceapi_java_demo;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.Calendar;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class MarketplaceAPI_Java_Demo {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception{
GetOrderInfo();
}
private static void GetOrderInfo() throws Exception{
System.out.println("[" + Calendar.getInstance().getTime() + "]Newegg Marketplace API - GetOrderInfo:");
System.out.println("-----------------------------------");
String requestUrl = "https://api.newegg.com/marketplace/ordermgmt/order/orderinfo?sellerid=A006";
try {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
URL url = new URL(requestUrl);
HttpsURLConnection httpsConnection = (HttpsURLConnection)url.openConnection();
//javax.net.ssl. = false;
//Set accepted format in response message:application/xml|application/json
httpsConnection.setRequestProperty("Accept", "application/xml");
//Set the accepted format in request body:application/xml|application/json
httpsConnection.setRequestProperty("content-type", "application/xml");
//Set the request method:GET|PUT|POST
httpsConnection.setRequestMethod("PUT");
//Set authorization key
httpsConnection.setRequestProperty("Authorization", "720ddc067f4d115bd544aff46bc75634");
//Set secret-key
httpsConnection.setRequestProperty("SecretKey", "21EC2020-3AEA-1069-A2DD-08002B30309D");
httpsConnection.setDoInput(true);
httpsConnection.setDoOutput(true);
String requestStr = "<NeweggAPIRequest>"
+ "<OperationType>GetOrderInfoRequest</OperationType>"
+ "<RequestBody>"
+ "<PageIndex>1</PageIndex>"
+ "<PageSize>10</PageSize>"
+ "<RequestCriteria>"
+ "<OrderNumberList>"
+ "<OrderNumber>159243598</OrderNumber>"
+ "<OrderNumber>41473642</OrderNumber>"
+ "</OrderNumberList>"
+ "<Status>1</Status>"
+ "<Type>1</Type>"
+ "<OrderDateFrom>2011-01-01 09:30:47</OrderDateFrom>"
+ "<OrderDateTo>2011-12-17 09:30:47</OrderDateTo>"
+ "<OrderDownloaded>0</OrderDownloaded>"
+ "</RequestCriteria>"
+ "</RequestBody>"
+ "</NeweggAPIRequest>";
byte[] requestBody = requestStr.getBytes();
//Set content-length
httpsConnection.setRequestProperty("Content-Length", String.valueOf(requestBody.length));
OutputStream outStream = httpsConnection.getOutputStream();
outStream.write(requestBody);
outStream.close();
InputStreamReader inputReader = new InputStreamReader(httpsConnection.getInputStream());
BufferedReader reader = new BufferedReader(inputReader);
String responseBody = "";
while(reader.ready()){
responseBody += reader.readLine();
}
reader.close();
inputReader.close();
System.out.println("[" + Calendar.getInstance().getTime() + "]Response Message:");
System.out.println("-----------------------------------");
System.out.println(responseBody);
} catch (MalformedURLException ex) {
System.out.println("Illegal request URI:" + ex.getMessage());
}
catch(Exception e){
System.out.println("Exception:" + e.getMessage());
//Error Handling for Bad Request
InputStreamReader errorReader = new InputStreamReader(httpsConnection.getErrorStream());
BufferedReader bufferReader = new BufferedReader(errorReader);
String errorMsg = "";
while(bufferReader.ready()){
errorMsg += bufferReader.readLine();
}
bufferReader.close();
errorReader.close();
System.out.println(errorMsg);
}
}
}
錯誤請求的異常處理(狀態碼=400)
try
{
//Your code here
}
catch(Exception e){
System.out.println("Exception:" + e.getMessage());
//Error Handling for Bad Request
InputStreamReader errorReader = new InputStreamReader(httpsConnection.getErrorStream());
BufferedReader bufferReader = new BufferedReader(errorReader);
String errorMsg = "";
while(bufferReader.ready()){
errorMsg += bufferReader.readLine();
}
bufferReader.close();
errorReader.close();
System.out.println(errorMsg);
}
PHP示例
下述代碼示範了如何在windows作業系統下用PHP curl模組來訪問新蛋商城API系統。
- 下載php_curl.dll
- 編輯php.ini並申請擴展:Extension=php_curl.dll
- 重啟Apache伺服器
示例:PHP,Get order status (獲取訂單狀態)
GET:
<?php
// Request Newegg API! REST Web Service using
// HTTP POST with curl. PHP4/PHP5
// Allows retrieval of HTTP status code for error reporting
error_reporting(E_ALL);
$SellerID = 'A006';
// The POST URL and parameters
// Please make sure your request URL is all in lower case
$request = 'https://api.newegg.com/marketplace/ordermgmt/orderstatus/orders/12345678?sellerid='.$SellerID;
$header_array =array('Content-Type:application/xml',
'Accept:application/xml',
'Authorization: your API-key here',
'SecretKey: your secretkey here');
try
{
// Get the curl session object
$session = curl_init($request);
// Set the POST options.
curl_setopt($session, CURLOPT_HEADER, 1);
curl_setopt($session,CURLOPT_HTTPHEADER,$header_array);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, 0);
// Do the POST and then close the session
$response = curl_exec($session);
curl_close($session);
print $response;
}
catch (InvalidArgumentException $e)
{
curl_close($session);
throw $e;
}
catch (Exception $e)
{
curl_close($session);
throw $e;
}
?>
示例:PHP,Get item inventory(獲取商品庫存數量)
POST:
<?php
// Request Newegg API! REST Web Service using
// HTTP POST with curl. PHP4/PHP5
// Allows retrieval of HTTP status code for error reporting
error_reporting(E_ALL);
$SellerID = 'A006';
// The POST URL and parameters
// Please make sure your request URL is all in lower case
$request = 'https://api.newegg.com/marketplace/contentmgmt/item/inventory?sellerid='.$SellerID;
$body = '<ContentQueryCriteria>
<Type>0</Type>
<Value>9SIA08I0492622</Value>
</ContentQueryCriteria>';
$header_array =array('Content-Type:application/xml',
'Accept:application/xml',
'Authorization: your API-key here',
'SecretKey: your secretkey here');
try
{
// Get the curl session object
$session = curl_init($request);
$putString = stripslashes($body);
$putData = tmpfile();
fwrite($putData, $putString);
fseek($putData, 0);
// Set the POST options.
curl_setopt($session, CURLOPT_HEADER, 1);
curl_setopt($session,CURLOPT_HTTPHEADER,$header_array);
curl_setopt($session, CURLOPT_POST, true);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($session, CURLOPT_POSTFIELDS, $body);
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($session, CURLOPT_INFILE, $putData);
curl_setopt($session, CURLOPT_INFILESIZE, strlen($putString));
// Do the POST and then close the session
$response = curl_exec($session);
curl_close($session);
print $response;
}
catch (InvalidArgumentException $e)
{
curl_close($session);
throw $e;
}
catch (Exception $e)
{
curl_close($session);
throw $e;
}
?>
示例:PHP,Update inventory and price(更新庫存和價格資訊)
PUT:
<?php
// Request Newegg API! REST Web Service using
// HTTP POST with curl. PHP4/PHP5
// Allows retrieval of HTTP status code for error reporting
error_reporting(E_ALL);
$SellerID = 'A006';
// The POST URL and parameters
// Please make sure your request URL is all in lower case
$request = 'https://api.newegg.com/marketplace/contentmgmt/item/inventoryandprice?sellerid='.$SellerID;
$body = '<ItemInventoryAndPriceInfo>
<Type>1</Type>
<Value>A006testitem201201021459</Value>
<Condition>1</Condition>
<Inventory>200</Inventory>
<MSRP>34.98</MSRP>
<SellingPrice>29.92</SellingPrice>
<EnableFreeShipping>1</EnableFreeShipping>
<Active>0</Active>
</ItemInventoryAndPriceInfo>';
$header_array =array('Content-Type:application/xml',
'Accept:application/xml',
'Authorization: your API-key here',
'SecretKey: your secretkey here');
try
{
// Get the curl session object
$session = curl_init($request);
$putString = stripslashes($body);
$putData = tmpfile();
fwrite($putData, $putString);
fseek($putData, 0);
// Set the POST options.
curl_setopt($session, CURLOPT_HEADER, 1);
curl_setopt($session,CURLOPT_HTTPHEADER,$header_array);
curl_setopt($session, CURLOPT_PUT, true);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($session, CURLOPT_POSTFIELDS, $body);
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($session, CURLOPT_INFILE, $putData);
curl_setopt($session, CURLOPT_INFILESIZE, strlen($putString));
// Do the POST and then close the session
$response = curl_exec($session);
curl_close($session);
print $response;
}
catch (InvalidArgumentException $e)
{
curl_close($session);
throw $e;
}
catch (Exception $e)
{
curl_close($session);
throw $e;
}
?>
下述代碼示範了怎樣在LINUX系統下用pecl http request擴展來訪問新蛋商城API系統。
- 從http://pecl.php.net/package/pecl_http 下載pecl_http擴展包,獲取最新的穩點版本。
- 安裝擴展包(參考:http://www.zipservers.com/community/showthread.php?59-How-to-install-PECL-Modules-on-Linux )
[root@server ]# cd /root/ ; wget http://pecl.php.net/get/pecl_http-1.6.5.tgz [root@server ]# tar -zxvf pecl_http-1.6.5.tgz [root@server ]# cd pecl_http-1.6.5 [root@server ]# phpize [root@server ]# ./configure [root@server ]# make [root@server ]# make test [root@server ]# make install [root@server ]# php -i | grep “Configuration File” Configuration File (php.ini) Path => /usr/local/lib Loaded Configuration File => /usr/local/lib/php.ini
- 在 php.ini文件中開啟擴展
[root@server ]# vi /usr/local/lib/php.ini And add extension=http.so
- 重啟Apache伺服器
示例:PHP,Get Item Inventory獲取商品庫存資訊
<?php
//request url
// Please make sure your request URL is all in lower case
$url =
" https://api.newegg.com/marketplace/contentmgmt/item/inventory?sellerid=A006";
//set the api-key & secret-key
$header_array = array('Authorization' => '{your API-key here}',
'Secretkey' => '{your secret-key here}');
//set the body if necessary
$body = "<ContentQueryCriteria>
<Condition>1</Condition>
<Type>0</Type>
<Value>9SIA0B992342342</Value>
</ContentQueryCriteria>";
$options = array(headers => $header_array);
//create the httprequest object
//specfiy the request method:HTTP_METH_GET|HTTP_METH_POST|HTTP_METH_PUT
$httpRequest_OBJ = new httpRequest($url, HTTP_METH_POST, $options);
//add the content type
$httpRequest_OBJ->setContentType = 'Content-Type: text/xml';
//add the raw post data
//$httpRequest_OBJ->setRawPostData ($body);
$httpRequest_OBJ->setBody ($body);
try
{
//send the http request
$result = $httpRequest_OBJ->send();
}catch(HttpException $ex)
{
if (isset($ex->innerException)){
echo $ex->innerException->getMessage();
exit;
} else {
echo $ex;
exit;
}
}
$response_code = $httpRequest_OBJ->getResponseCode();
if($response_code == "200")
{
//reqeust success
echo $response_code;
echo $httpRequest_OBJ->getResponseBody();
}
else
{
//failure
echo $response_code;
echo $httpRequest_OBJ->getResponseBody();
}
?>
錯誤請求的異常處理(狀態碼:400)
// Do the POST and then close the session $response = curl_exec($session); curl_close($session); //The error message will be stored in this variable if it’s a bad request print $response;
Python示例
下述代碼示範了如何運用Python語言訪問新蛋商城API系統。
示例:Python,Get Item Price (獲取商品價格資訊)
import httplib2
#import pyodbc
import string
all_items_location_id=521799450
# whether to print item data retrieved from database
print_item_data=True
# items data retrieved from database
items=[]
def _put_call(url, xmlfeed):
h = httplib2.Http(".cache",disable_ssl_certificate_validation=True)
resp, content = h.request(url, "POST", body=xmlfeed, headers={'content-type':'application/xml','Authorization': 'your API-key here', 'Secretkey':'your secretkey here' } )
print "response header from Newegg:", resp
print "response body from Newegg:", content
def get_price():
header = '<?xml version="1.0" encoding="UTF-8"?>'
xmlfeed=[]
xmlfeed.append(header)
xmlfeed.append('<ContentQueryCriteria>')
xmlfeed.append('<Type>1</Type>')
xmlfeed.append('<Value>TCR8996</Value>')
xmlfeed.append('</ContentQueryCriteria>')
xmlfeed=string.join(xmlfeed,'')
print "Get item price:"
put_call_url = 'https://api.newegg.com/marketplace/contentmgmt/item/price?sellerid=A006'
_put_call(put_call_url,xmlfeed)
get_price()
錯誤請求的異常處理(狀態碼:400)
def _put_call(url, xmlfeed):
h = httplib2.Http(".cache",disable_ssl_certificate_validation=True)
resp, content = h.request(url, "POST", body=xmlfeed, headers={'content-type':'application/xml','Authorization': 'your API-key here', 'Secretkey':'your secretkey here' } )
print "response header from Newegg:", resp
#The error message will be stored in this variable if it’s a bad request
print "response body from Newegg:", content
更新日期:10/15/2018