首页 > 代码库 > 分享下速卖通api的java的入门代码
分享下速卖通api的java的入门代码
package com.print.base;
import java.io.*;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
// Referenced classes of package com.print.base:
// postdata, UploadPhoneBankFile
/**
* 速卖通操作维护类
*/
public class smt
{
public String client_id;
public String client_key;
public String site;
/**
* 构造函数,默认前15个店铺的idkey
*/
public smt()
{
client_id = "";
client_key = "";
site = "aliexpress";
}
/**
* 构造函数 必须有店铺名
* @param shopname
*/
public smt(String shopname)
{
Map map= (Map) Base1.getMapbySQL("select client_id, client_key from t_smt_baseshop where fshop_name=‘" + shopname +"‘");
client_id = (String) map.get("client_id");
client_key = (String) map.get("client_key");
site = "aliexpress";
}
/**
* 根据店铺名获取token
* @param shopname
* @return
*/
public String gettokenbyshopname(String shopname)
{
String sql= "select FShop_tokenyear,FShop_SysUser from t_smt_shop where fshop_name=‘" + shopname +"‘";//fshop_user=‘info@eforchina.com‘";
Map mapmain=(Map) Base1.getMapbySQL(sql);
String token = "";
String tokenyear =(String)mapmain.get("FShop_tokenyear");
String ShopName =(String)mapmain.get("FShop_Name");
String FShop_SysUser =(String)mapmain.get("FShop_SysUser");
String rt = GetTokenByTokenYear(tokenyear);
try
{
JSONObject jsonObject = JSONObject.fromObject( rt );
token=jsonObject.get("access_token").toString();
}
catch(Exception ex)
{
String subject= FShop_SysUser+"的速卖通店铺"+ ShopName+"登陆失效请重新登陆";
Base1.sendmail(subject,"",""); //todo 修改为32
return "broke";
}
return token;
}
/**
* 创建邮政小包物流订单
* 传入速卖通运单id
*/
public boolean getPDFFile(String internationalLogisticsId,String shopname)
{
String token = gettokenbyshopname(shopname);
Map<String, String> map = new TreeMap<String, String>();
map.put("internationalLogisticsId",internationalLogisticsId);
String postdata=http://www.mamicode.com/"";
String param="";
Set<String> keySet = map.keySet();
Iterator<String> iter = keySet.iterator();
while(iter.hasNext())
{
String key = iter.next();
// System.out.println(key+"----------------------------------"+map.get(key));
if (postdata.length()<1)
{
postdata=http://www.mamicode.com/postdata + "" + key + "=" + map.get(key);
}
else
{
postdata=http://www.mamicode.com/postdata + "&" + key + "=" + map.get(key).toString() ;
}
param=param + key + map.get(key).toString();
}
String url="http://gw.api.alibaba.com/openapi/param2/1/aliexpress.open/api.createWarehouseOrder/" + client_id;
param="param2/1/aliexpress.open/api.createWarehouseOrder/" + client_id + param;
String sign =hmac_sha1(param,client_key).toUpperCase();
postdata=http://www.mamicode.com/postdata + "&_aop_signature=" + sign;
String filepath ="";
try
{
GetFileByUrl(url + "?" + postdata,filepath);
}
catch (Exception ex)
{
System.out.print("获取pdf失败" + ex.getMessage());
return false;
}
return true;
}
/**
* * 创建邮政小包物流订单 (目前只支持俄罗斯物流)
*
* @param smtid 传入速卖通订单id
* @param shopname
* @return
*/
public String createWarehouseOrder(String smtid,String shopname)
{
String tradeOrderId =smtid;; // 是 交易订单号 60000970354018
String tradeOrderFrom ="Sourcing";// 是 交易订单来源,AE订单为ESCROW Sourcing订单为“SOURCING” ESCROW
String warehouseCarrierService =""; // 是 用户选择的实际发货物流服务(物流服务key,即仓库服务名称) CPAM_WLB_FPXSZ;CPAM_WLB_CPHSH;CPAM_WLB_ZTOBJ
String domesticLogisticsCompanyId ="500"; // 是 国内快递ID 505(物流公司是other时,ID为-1) //中通500
String domesticLogisticsCompany ="中通快递"; // 否 国内快递公司名称 物流公司Id为-1时,必填
String domesticTrackingNo =""; // 是 国内快递运单号,长度1-32 123231231
String token = gettokenbyshopname(shopname);
if (token.equals(""))
{
return "err:没有token";
}
String rt="";
String sql = "select top 1 a.* "
+ " from T_PurchaseOrder a WITH (NOLOCK) ,T_smt_Order b WITH (NOLOCK) "
+ " where a.fordernumber=b.fordernumber and b.a_smtid=‘" + smtid +"‘";
List ls =Base1.getListbySQL(sql);
if (ls.size()==0)
{
return "err:没有此订单";
}
sql = "select count(1) from t_purchaseorderdetail where FPurchaseOrderID ==‘ali" + smtid +"‘ and "
+ " fgoodstype in (2,4,16,32,1024,2048) ";
String ishavedian=Base1.getStringbySQL(sql);
if (!ishavedian.equals("0"))
{
//return "err:货物带电池";
}
Map mp=(Map) ls.get(0);
sql = "select Fcurrentprice,isnull(frealoneweight,500) as frealoneweight,c.finvoicecnname,c.FInvoiceEnName"
+ " from t_smt_order_detail a ,t_product b, t_type c "
+ " where a_smtid=‘" + smtid +"‘ and a.itemnumber=b.fproductitemno and "
+ " b.ftype_id=c.ftype_id ";
Map mp2 = Base1.getMapbySQL(sql);
System.out.print(sql);
String remark = String.valueOf(mp.get("FOrderNumber"));
String categoryCnDesc = String.valueOf(mp2.get("finvoicecnname"));
String categoryEnDesc = String.valueOf(mp2.get("FInvoiceEnName"));
String productid = String.valueOf(mp2.get("productid"));
String productnum = String.valueOf(mp2.get("lognum"));
String productWeight = String.valueOf(mp2.get("frealoneweight"));
String isContainsBattery= "0" ;
String adminMemberSeq = ""; //这个参数 暂作忽略
String city = String.valueOf(mp.get("FOrderCity"));
String country = String.valueOf(mp.get("FOrderCountry"));
String email = String.valueOf(mp.get("FThisCustomerEmail"));
String fax = "";
String memberSeq = "";
String memberType = "";
String mobile = String.valueOf(mp.get("FOrderTel"));
String name = String.valueOf(mp.get("FOrderTel"));
String phone = String.valueOf(mp.get("FOrderTel"));
String postcode = String.valueOf(mp.get("FOrderZipcode"));
String province = String.valueOf(mp.get("FOrderState"));
String streetAddress = String.valueOf(mp.get("FOrderAddress")).replace("/", "");
String trademanageId = "";
String declareProductDTOs="[{\"categoryCnDesc\":\"" + categoryCnDesc + "\",\"categoryEnDesc\":\"" + categoryEnDesc + "\",\"isContainsBattery\":"
+ isContainsBattery + "\",\"productDeclareAmount\":1,\"productId\":" + productid + ",\"productNum\":" +productnum +",\"productWeight\":" +productWeight+"}]";
JSONObject json = new JSONObject();
JSONArray array = new JSONArray();
JSONObject productJSON = new JSONObject();
productJSON.element("id", 1);
array.add(productJSON);
json.element("receiver", array); // {receiver:[{product:1}]}}
json.toString();
String addressDTOs="{\"receiver\":{\"adminMemberSeq\":" + adminMemberSeq
+ ",\"city\":\"" + city + "\",\"country\":\"" + country + "\",\"email\":\""
+ email + "\",\"fax\":\"" + fax + "\",\"memberSeq\":"
+ memberSeq + ",\"memberType\":\"" + memberType + "\",\"mobile\":\""
+ mobile + "\",\"name\":\"" + name + "\",\"phone\":\""
+ phone + "\",\"postcode\":\"" + postcode + "\",\"province\":\""
+ province + "\",\"streetAddress\":\"" + streetAddress + " \",\"trademanageId\":\""
+ trademanageId + "\"},\"sender\":{\"adminMemberSeq\":,\"city\":\"440300\""
+ ",\"country\":\"CN\",\"county\":\"310115\",\"email\":\"\","
+ "\"memberSeq\":,\"memberType\":\"sender\",\"name\":\"huangyaochun\","
+ "\"phone\":\"\",\"postcode\":\"\",\"province\":\"\",\"streetAddress"
+ "\":\"4/F, No.71,Buji Rd. Buji Post Office, Buji Longgang\",\"trademanageId\":\"hjy_seller\"}}";
if (1==1)
{
return declareProductDTOs;
}
Map<String, String> map = new TreeMap<String, String>();
map.put("tradeOrderId",tradeOrderId);
map.put("tradeOrderFrom",tradeOrderFrom);
map.put("warehouseCarrierService",warehouseCarrierService);
map.put("domesticLogisticsCompanyId",domesticLogisticsCompanyId);
map.put("domesticLogisticsCompany",domesticLogisticsCompany);
map.put("domesticTrackingNo",domesticTrackingNo);
map.put("declareProductDTOs",declareProductDTOs);
map.put("addressDTOs",addressDTOs);
map.put("remark",remark);
map.put("access_token",token);
String postdata=http://www.mamicode.com/"";
String param="";
Set<String> keySet = map.keySet();
Iterator<String> iter = keySet.iterator();
while(iter.hasNext())
{
String key = iter.next();
// System.out.println(key+"----------------------------------"+map.get(key));
if (postdata.length()<1)
{
postdata=http://www.mamicode.com/postdata + "" + key + "=" + map.get(key);
}
else
{
postdata=http://www.mamicode.com/postdata + "&" + key + "=" + map.get(key).toString() ;
}
param=param + key + map.get(key).toString();
}
String url="http://gw.api.alibaba.com/openapi/param2/1/aliexpress.open/api.createWarehouseOrder/" + client_id;
param="param2/1/aliexpress.open/api.createWarehouseOrder/" + client_id + param;
String sign =hmac_sha1(param,client_key).toUpperCase();
postdata=http://www.mamicode.com/postdata + "&_aop_signature=" + sign;
rt=doGet(url + "?" + postdata);
return rt;
}
/**
* getloginurl
* @param redirect_uri
* @return
*/
public String GetLoginUrl(String redirect_uri)
{
String param = (new StringBuilder("client_id=")).append(client_id).append("&site=aliexpress&redirect_uri=").append(redirect_uri).toString();
String param1 = (new StringBuilder("client_id")).append(client_id).append("redirect_uri").append(redirect_uri).append("site").append(site).toString();
String sign = hmac_sha1(param1, client_key).toUpperCase();
return (new StringBuilder("http://gw.api.alibaba.com/auth/authorize.htm?")).append(param).append("&_aop_signature=").append(sign).toString();
}
/**
* gettoken by code
* @param code
* @param redirect_uri
* @return
*/
public String GetTokenByCode(String code, String redirect_uri)
{
String url = (new StringBuilder("https://gw.api.alibaba.com/openapi/http/1/system.oauth2/getToken/")).append(client_id).toString();
String grant_type = "authorization_code";
String need_refresh_token = "true";
String postdata = http://www.mamicode.com/(new StringBuilder("grant_type=")).append(grant_type).append("&need_refresh_token=").append(need_refresh_token).append("&client_id=").append(client_id).append("&client_secret=").append(client_key).append("&redirect_uri=").append(redirect_uri).append("&code=").append(code).toString();
postdata post = new postdata();
// System.out.print(postdata);
post.setURL(url);
post.sendPost(postdata);
String rt = post.getContent();
return rt;
}
/**
* get token by tokenyear
* @param tokenyear
* @return
*/
public String GetTokenByTokenYear(String tokenyear)
{
String grant_type = "refresh_token";
String param = (new StringBuilder("client_id=")).append(client_id).append("&client_secret=").append(client_key).append("&grant_type=").append(grant_type).append("&refresh_token=").append(tokenyear).toString();
String param1 = (new StringBuilder("client_id")).append(client_id).append("client_secret").append(client_key).append("grant_type").append(grant_type).append("refresh_token").append(tokenyear).toString();
param1 = (new StringBuilder("param2/1/system.oauth2/refreshToken/")).append(client_id).append(param1).toString();
String sign = hmac_sha1(param1, client_key).toUpperCase();
String url = (new StringBuilder("https://gw.api.alibaba.com/openapi/param2/1/system.oauth2/refreshToken/")).append(client_id).toString();
param = (new StringBuilder(String.valueOf(param))).append("&_aop_signature=").append(sign).toString();
postdata post = new postdata();
// System.out.print("dddddddd");
url = (new StringBuilder(String.valueOf(url))).append("?").append(param).toString();
// System.out.print(url);
post.setURL(url);
post.sendPost("");
String rt = post.getContent();
return rt;
}
/**
* 更新组
* @param token
* @param ShopName
* @return
*/
public String refreshGroup(String token, String ShopName)
{
String methodname = "api.getWsProductGroup";
String postdata = http://www.mamicode.com/(new StringBuilder("access_token=")).append(token).append("&page=1").toString();
String param = (new StringBuilder("param2/1/aliexpress.open/")).append(methodname).append("/").append(client_id).append("access_token").append(token).append("page1").toString();
String sign = hmac_sha1(param, client_key).toUpperCase();
postdata = http://www.mamicode.com/(new StringBuilder(String.valueOf(postdata))).append("&_aop_signature=").append(sign).toString();
String rt = getDataByAPI(methodname, token, postdata);
// System.out.print(rt);
return rt;
}
/**
* 更新当前运费模板
* @param token
* @param ShopName
* @return
*/
public String refreshFreightTemplate(String token, String ShopName)
{
String methodname = "api.listFreightTemplate";
String postdata = http://www.mamicode.com/(new StringBuilder("access_token=")).append(token).append("&page=1").toString();
String param = (new StringBuilder("param2/1/aliexpress.open/")).append(methodname).append("/").append(client_id).append("access_token").append(token).append("page1").toString();
String sign = hmac_sha1(param, client_key).toUpperCase();
postdata = http://www.mamicode.com/(new StringBuilder(String.valueOf(postdata))).append("&_aop_signature=").append(sign).toString();
String rt = getDataByAPI(methodname, token, postdata);
// System.out.print(rt);
return rt;
}
public List getListbyFreightTemplateString(String rt)
{
List ls = new ArrayList();
Map mp = new TreeMap();
JSONObject json = JSONObject.fromObject(rt);
rt = json.get("aeopFreightTemplateDTOList").toString();
JSONArray array = JSONArray.fromObject(rt);
for(int i = 0; i < array.size(); i++)
{
String str1 = array.get(i).toString();
JSONObject jsonObject = JSONObject.fromObject(str1);
mp = new HashMap(2);
mp.put("name", jsonObject.get("templateName").toString());
mp.put("id", jsonObject.get("templateId").toString());
ls.add(mp);
}
return ls;
}
public List getListbyGroupString(String rt)
{
List ls = new ArrayList();
Map mp = new TreeMap();
JSONObject json = JSONObject.fromObject(rt);
rt = json.get("aeProductGroupList").toString();
JSONArray array = JSONArray.fromObject(rt);
for(int i = 0; i < array.size(); i++)
{
String str1 = array.get(i).toString();
JSONObject jsonObject = JSONObject.fromObject(str1);
mp = new HashMap(2);
mp.put("name", jsonObject.get("name").toString());
mp.put("id", jsonObject.get("id").toString());
ls.add(mp);
}
return ls;
}
public String getDataByAPI(String methodname, String token, String postdata)
{
String url = (new StringBuilder("http://gw.api.alibaba.com/openapi/param2/1/aliexpress.open/")).append(methodname).append("/").append(client_id).toString();
//System.out.print((new StringBuilder("url=")).append(url).toString());
String rt = "";
HttpGet get = new HttpGet((new StringBuilder(String.valueOf(url))).append("?").append(postdata).toString());
try
{
URL url1 = new URL((new StringBuilder(String.valueOf(url))).append("?").append(postdata).toString());
java.io.InputStream in = url1.openStream();
BufferedReader bin = new BufferedReader(new InputStreamReader(in, "UTF-8"));
for(String s = null; (s = bin.readLine()) != null;)
{
// System.out.println(s);
rt = (new StringBuilder(String.valueOf(rt))).append(s).toString();
}
bin.close();
}
catch(Exception exception) { }
return rt;
}
public static TreeMap getmapbyjson(String rt)
{
rt = rt.replace("{", "").replace("}", "");
TreeMap rate = new TreeMap();
String arj[] = rt.split(",");
for(int i = 0; i < arj.length; i++)
{
arj[i] = arj[i].replace("\":", "~");
String arj1[] = arj[i].split("~");
if(arj1.length > 1)
{
String name = arj1[0].replace("\"", "");
String value = http://www.mamicode.com/arj1[1].replace("/"", "");
//System.out.print(name);
//System.out.print(value);
rate.put(name, value);
}
}
return rate;
}
public static String uploadpic(String filename, String client_id, String token, String client_key)
{
String filepath = (new StringBuilder("c:\\eforchina\\")).append(filename).toString();
filename = "S-IP5G-0367B_1.jpg";
String url = (new StringBuilder("http://gw.api.alibaba.com/fileapi/param2/1/aliexpress.open/api.uploadImage/")).append(client_id).append("?access_token=").append(token).append("&fileName=").append(filename).toString();
String param = (new StringBuilder("param2/1/aliexpress.open/api.uploadImage/")).append(client_id).append("access_token").append(token).append("fileName").append(filename).toString();
String sign = hmac_sha1(param, client_key).toUpperCase();
// System.out.print((new StringBuilder("filename=")).append(filename).toString());
//System.out.print((new StringBuilder("filepath=")).append(filepath).toString());
url = (new StringBuilder(String.valueOf(url))).append("&_aop_signature=").append(sign).toString();
File file = new File(filepath);
String rt1 = "";
try
{
rt1 = UploadPhoneBankFile.submit(url, filepath, file, "gb2312");
}
catch(Exception ex)
{
return (new StringBuilder("-1~")).append(ex.getMessage()).toString();
}
return rt1;
}
public static String hmac_sha1(String value, String key)
{
try
{
byte keyBytes[] = key.getBytes();
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
byte rawHmac[] = mac.doFinal(value.getBytes());
String hexBytes = byte2hex(rawHmac);
return hexBytes;
}
catch(Exception e)
{
throw new RuntimeException(e);
}
}
private static String byte2hex(byte b[])
{
String hs = "";
String stmp = "";
for(int n = 0; n < b.length; n++)
{
stmp = Integer.toHexString(b[n] & 0xff);
if(stmp.length() == 1)
hs = (new StringBuilder(String.valueOf(hs))).append("0").append(stmp).toString();
else
hs = (new StringBuilder(String.valueOf(hs))).append(stmp).toString();
}
return hs;
}
private static String appendEqualSign(String s)
{
int len = s.length();
int appendNum = 8 - len / 8;
for(int n = 0; n < appendNum; n++)
s = (new StringBuilder(String.valueOf(s))).append("%3D").toString();
return s;
}
public static byte[] hexStringToByte(String hex)
{
int len = hex.length() / 2;
byte result[] = new byte[len];
char achar[] = hex.toCharArray();
for(int i = 0; i < len; i++)
{
int pos = i * 2;
result[i] = (byte)(toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}
private static byte toByte(char c)
{
byte b = (byte)"0123456789ABCDEF".indexOf(c);
return b;
}
public static String doGet(String url)
{
String strResult = null;
//System.out.println((new StringBuilder("url1=")).append(url).toString());
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try
{
HttpResponse httpResponse = client.execute(httpGet);
//System.out.println((new StringBuilder("\u5F02\u5E382=")).append(httpResponse.getStatusLine().getStatusCode()).toString());
if(httpResponse.getStatusLine().getStatusCode() == 500 || httpResponse.getStatusLine().getStatusCode() == 400 || httpResponse.getStatusLine().getStatusCode() == 200 || httpResponse.getStatusLine().getStatusCode() == 409)
strResult = EntityUtils.toString(httpResponse.getEntity());
}
catch(ClientProtocolException e)
{
e.printStackTrace();
System.out.print((new StringBuilder("\u5F02\u5E38=")).append(e.getMessage()).toString());
}
catch(IOException e)
{
e.printStackTrace();
System.out.print((new StringBuilder("\u5F02\u5E38=")).append(e.getMessage()).toString());
}
//System.out.print((new StringBuilder("strResult=")).append(strResult).toString());
return strResult;
}
/**
* 获取url 二进制文件
* @param url
* @param path
* @throws IOException
*/
public static void GetFileByUrl(String url, String path) throws IOException
{
HttpClient client = new HttpClient();
HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
params.setConnectionTimeout(15000);
params.setSoTimeout(15000);
HostConfiguration hostConfig = new HostConfiguration();
GetMethod method = new GetMethod(url);
InputStream in = null;
OutputStream out = null;
try {
int statusCode = client.executeMethod(hostConfig, method);
if (statusCode == HttpStatus.SC_NOT_FOUND) {
throw new FileNotFoundException();
} else if (statusCode != HttpStatus.SC_OK) {
throw new IOException("status: " + statusCode);
}
in = method.getResponseBodyAsStream();
out = new FileOutputStream(path);
IOUtils.copy(in, out);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
method.releaseConnection();
}
}
public static String doPost(String url, Map params)
throws IllegalStateException, IOException
{
String strResult = "";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List postData = http://www.mamicode.com/new ArrayList();
java.util.Map.Entry entry;
for(Iterator iterator = params.entrySet().iterator(); iterator.hasNext(); System.out.print((String)entry.getValue()))
{
entry = (java.util.Map.Entry)iterator.next();
postData.add(new BasicNameValuePair((String)entry.getKey(), (String)entry.getValue()));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, "UTF-8");
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
if(response.getStatusLine().getStatusCode() == 200)
strResult = EntityUtils.toString(response.getEntity());
return strResult;
}
}