拼多多商品推广转链

平多多平台接入文档 http://open.pinduoduo.com/#/document
API文档: http://open.pinduoduo.com/#/apidocument

所有的API都需要‘签名’

拼多多商品推广转链_第1张图片
image

签名工具类:


import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author MkStone [email protected]
 * @date 2018/6/17 21:35
 */
@Component
public class MD5_Sign {

    public  static   String client_id="你的 client_id";

    public  static  String client_secret="你的client_secret";


    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UTF-8 is unsupported", e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MessageDigest不支持MD5Util", e);
        }
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    /**
     * md5签名
     *
     * 按参数名称升序,将参数值进行连接 签名
     * @param params
     * @return
     */
    public static String sign( TreeMap params) {
        StringBuilder paramValues = new StringBuilder();
        params.put("client_id", client_id);
        for (Map.Entry entry : params.entrySet()) {
            paramValues.append(entry.getKey()+entry.getValue());
        }

        /*  //拼多多 签名认证
         *签名算法

            POP目前支持的签名算法为:MD5(sign_method=md5),签名大体过程如下:

            1-所有参数进行按照首字母先后顺序排列

            2-把排序后的结果按照参数名+参数值的方式拼接

            3-拼装好的字符串首尾拼接client_secret进行md5加密后转大写,secret的值是拼多多开放平台后台分配的client_secret
          *
          * */
        System.out.println(client_secret+paramValues.toString()+client_secret);
        String Md5Sign=md5(client_secret+paramValues.toString()+client_secret).toUpperCase();
        System.out.println(Md5Sign);
        return Md5Sign;
    }


    /**
     * 请求参数签名验证
     *
     * @param request
     * @return true 验证通过 false 验证失败
     * @throws Exception
     */
    public static boolean verifySign(HttpServletRequest request) throws Exception {
        TreeMap params = new TreeMap();

        String signStr = request.getParameter("sign");
        if(StringUtils.isBlank(signStr)){
            throw new RuntimeException("There is no signature field in the request parameter!");
        }

        Enumeration enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String paramName = enu.nextElement().trim();
            if (!paramName.equals("sign")) {
                params.put(paramName, URLDecoder.decode(request.getParameter(paramName), "UTF-8"));
            }
        }

        if (!sign(params).equals(signStr)) {
            return false;
        }
        return true;
    }

如何使用?

    //签名
  String sign="";
 TreeMap map=new TreeMap();
        //商品
        map.put("goods_id_list","["+GoodsId+"]");
        map.put("type",type);

        map.put("p_id",pid);
        map.put("generate_short_url","true");
        map.put("data_type","JSON");
        map.put("timestamp",timestam);
        sign = MD5_Sign.sign(map);

多多客商品转链 ddk_link(id,GoodsId);

public  String ddk_link(String pid,String GoodsId){
        String url="http://gw-api.pinduoduo.com/api/router?";
        //参数
        String timestam=(new Date().getTime()/1000)+"";
        String sign="";
        TreeMap<String,String> map=new TreeMap<String, String>();
        //商品
        map.put("goods_id_list","["+GoodsId+"]");
        map.put("type",type);

        map.put("p_id",pid);
        map.put("generate_short_url","true");
        map.put("data_type","JSON");
        map.put("timestamp",timestam);
        sign = MD5_Sign.sign(map);
        //type 值
        url+="type="+type;
        // 返回值类型
        url+="&data_type=JSON";
        //ClienmtID
        url+="&client_id="+client_id;
        //商品ID
        url+="&goods_id_list=["+GoodsId+"]";
        //推广位ID
        url+="&p_id="+pid;
        // 是否生成短链接,true-是,false-否
        url+="&generate_short_url=true";
        url+="×tamp="+timestam;
        url+="&sign="+sign;

        return loadJSON(url);
    }
    public String loadJSON (String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) oracle.openConnection();
           connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.connect();

            BufferedReader in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));

            String inputLine = null;
            while ( (inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (IOException e) {
            return "-1";
        }
        return json.toString();
    }

你可能感兴趣的:(java)