创建自用源码库
您可以创建自己的源码库来连接新蛋商城的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系统。
步骤1 – 下载php_curl.dll
步骤2 – 编辑php.ini并申请扩展:Extension=php_curl.dll
步骤3 – 重启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