分享下速卖通api的java的入门代码

code 同时被 2 个专栏收录
18 篇文章 0 订阅
3 篇文章 0 订阅

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="";
     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=postdata + "" + key + "=" + map.get(key);
     }
     else
     {
      postdata=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=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="";
     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=postdata + "" + key + "=" + map.get(key);
     }
     else
     {
      postdata=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=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("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 = (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 = (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 = (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 = (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 = (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("

  • 0
    点赞
  • 3
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

打赏
文章很值,打赏犒劳作者一下
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页

打赏

nittystone

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值