调用实例

Java实现

1、RestTemplate 请求方式

//请求APP_KEY
public static final String APP_KEY = "98ee362b4981c29ff7c932650d4e768c";
//请求APP_SECRET
public static final String APP_SECRET = "1f2cc41322bef232098c563457c4f492";
//请求地址
public static final String SERVER_URL = "http://open.2dfire-daily.com/router";

// 1、将除“sign”外的所有参数按key进行字典升序排列,按key排序后的参数(keyvalue)拼接起来。

// 2、使用secret对keyvalue按首尾进行拼接(如:secretkey1value1key2value2...secret)

// 3、使用SHA1对secret拼接好的字符串进行加密。

// 4、使用hex对SHA1加密后的字符转进行转换

// 5、将转换之后的字符串字母转成大写

// 注;uppercase(hex(sha1(secretkey1value1key2value2...secret))

// 举例:

// 1、secret:3305DB4787E472D18DC8651DFB0A3CE5

// 2、登录参数:

{method=dfire.users.login, appKey=05AA200AAE5893E9C08826F71856C380, v=1.0, locale=zh_CN, userName=maodou, timestamp=1449715500956, password=C0D4C5093500E077EC8DBBAEB17E3A24}

// 3、拼接后字符串:

3305DB4787E472D18DC8651DFB0A3CE5appKey05AA200AAE5893E9C08826F71856C380localezh_CNmethoddfire.users.loginpasswordC0D4C5093500E077EC8DBBAEB17E3A24timestamp1449715500956userNamemaodouv1.03305DB4787E472D18DC8651DFB0A3CE5

// 4、加密后:042F93BF86B50806DC089E57282CA9200F38B459

/**
 * usersLogin(用户登录,返回sessionId)
 * @Exception 异常对象
 */

@org.junit.Test

public void usersLogin() throws Exception {

 RestTemplate restTemplate = new RestTemplate();

 MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();

 form.add("method", "dfire.users.login");

 form.add("appKey", APP_KEY);

 form.add("v", "1.0");

 form.add("timestamp", String.valueOf(System.currentTimeMillis()));

 form.add("userName", "waimai2");

 form.add("password", MD5Util.MD5Encode("123456","utf-8"));

 //对请求参数列表进行签名

 String sign = RopUtils.sign(form.toSingleValueMap(), APP_SECRET);

 form.add("sign", sign);

 String response = restTemplate.postForObject(SERVER_URL, form, String.class);

 System.out.println("response:\n" + response);
}


/**
 * 店铺外部关系查询
 * @throws Exception
 */

@org.junit.Test

public void shopExternalSearch() throws Exception {

 RestTemplate restTemplate = new RestTemplate();

 MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();

 form.add("method", "dfire.shop.external.search");

 form.add("appKey", APP_KEY);

 form.add("v", "1.0");

 form.add("timestamp", String.valueOf(System.currentTimeMillis()));

 //对请求参数列表进行签名

 String sign = RopUtils.sign(form.toSingleValueMap(), APP_SECRET);

 form.add("sign", sign);

 form.add("sessionId", SESSION_ID);

 String response = restTemplate.postForObject(SERVER_URL, form, String.class);

 System.out.println("response:\n" + response);
}

/**
 * 商品类目接口
 * @throws Exception
 */
@org.junit.Test

public void kindmenuQuery() throws Exception {

 RestTemplate restTemplate = new RestTemplate();

 MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();

 form.add("method", "dfire.kindmenu.query");

 form.add("appKey", APP_KEY);

 form.add("v", "1.0");

 form.add("timestamp", String.valueOf(System.currentTimeMillis()));

 form.add("entityId", "99180959");

 //对请求参数列表进行签名

 String sign = RopUtils.sign(form.toSingleValueMap(), APP_SECRET);

 form.add("sign", sign);

 form.add("sessionId", SESSION_ID);

 String response = restTemplate.postForObject(SERVER_URL, form, String.class);

 System.out.println("response:\n" + response);
}

2、HttpClient 请求方式

@Test
public  void getShopOrderList() throws Exception {

    Map<String, String> form = new HashMap<String, String>();

    form.put("method", "dfire.shop.order.list");

    form.put("appKey", APP_KEY);

    form.put("v", "1.0");

    form.put("timestamp", String.valueOf(System.currentTimeMillis()));

    //具体参数

    form.put("entityId", "3344");//参数:店铺Id

    form.put("currDate", "20161013");//参数:日期

    //对请求参数列表进行签名

    String sign = RopUtils.sign(form, APP_SECRET);

    form.put("sign", sign);


    //HttpClient 请求方式

    DefaultHttpClient httpclient = new DefaultHttpClient();

    // 目标地址

    HttpPost httppost = new HttpPost(SERVER_URL);

    System.out.println("请求: " + httppost.getRequestLine());

    // post 参数 传递

    List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();

    Map<String,String> params=new HashMap<>();

    for(String key:form.keySet()){

    nvps.add(new BasicNameValuePair(key, String.valueOf(form.get(key)))); // 参数

    }

    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);

    httppost.setEntity(formEntity); // 设置参数给Post

    // 执行

    HttpResponse response = httpclient.execute(httppost);

    HttpEntity entity = response.getEntity();

    if (entity != null) {

    // 显示结果

    BufferedReader reader = new BufferedReader(new InputStreamReader(
                    entity.getContent(), "UTF-8"));

    String line = null;

    while ((line = reader.readLine()) != null) {

            System.out.println(line);

    }

    }
    }

3、SDK 请求方式

JAVA SDK下载

实例代码

import com.alibaba.fastjson.JSONObject;
import com.dfire.api.client.DefaultDfireClient;
import com.dfire.api.request.ShopDayStatisticDataRequest;
import com.dfire.api.response.ShopDayStatisticDataResponse;
import com.dfire.api.vo.ShopStatisticsDayVo;

public class DfireSampleClient {

        private static final String APP_KEY = "cdc08577b61942442aa89390dacb25ad";
        private static final String APP_SECRET = "1c0800e19b7fae2c256ed6eebfb315c2";
        public static final String SERVER_URL = "http://open.2dfire-daily.com/router";

        private static DefaultDfireClient dfireClient = new DefaultDfireClient(SERVER_URL, APP_KEY, APP_SECRET);

        public static void main(String[] args) throws Exception{
                ShopDayStatisticDataRequest request = new ShopDayStatisticDataRequest();
                request.setEntityId("3344");
                request.setCurrDate("20160517");
                String response = dfireClient.buildClientRequest()
                                .post(request, "dfire.shop.day.statistic.data", "1.0");
                System.out.println(response);
                ShopDayStatisticDataResponse result = JSONObject.parseObject(response, ShopDayStatisticDataResponse.class);
                if(result.isSuccess()){
                        ShopStatisticsDayVo data = result.getModel();
                        System.out.println(data.getEntityId());
                }

        }
}

4、加密部分

import java.security.MessageDigest;

public class MD5Util {

        private static String byteArrayToHexString(byte b[]) {
                StringBuffer resultSb = new StringBuffer();
                for (int i = 0; i < b.length; i++)
                        resultSb.append(byteToHexString(b[i]));

                return resultSb.toString();
        }

        private static String byteToHexString(byte b) {
                int n = b;
                if (n < 0)
                        n += 256;
                int d1 = n / 16;
                int d2 = n % 16;
                return hexDigits[d1] + hexDigits[d2];
        }

        public static String MD5Encode(String origin, String charsetname) {
                String resultString = null;
                try {
                        resultString = new String(origin);
                        MessageDigest md = MessageDigest.getInstance("MD5");
                        if (charsetname == null || "".equals(charsetname))
                                resultString = byteArrayToHexString(md.digest(resultString
                                                .getBytes()));
                        else
                                resultString = byteArrayToHexString(md.digest(resultString
                                                .getBytes(charsetname)));
                } catch (Exception exception) {
                }
                return resultString;
        }

        private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
                        "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

}

5、签名部分

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.security.GeneralSecurityException;

import java.security.MessageDigest;

import java.util.*;

public class RopUtils {

        private static final Logger errorLogger = LoggerFactory.getLogger("error");

        /**
         * 使用<code>secret</code>对paramValues按以下算法进行签名: <br/>
         * uppercase(hex(sha1(secretkey1value1key2value2...secret))
         *
         * @param paramValues 参数列表
         * @param secret
         * @return
         */
        public static String sign(Map<String, String> paramValues, String secret) {

                return sign(paramValues,null,secret);

        }

        /**
         * 对paramValues进行签名,其中ignoreParamNames这些参数不参与签名
         * @param paramValues
         * @param ignoreParamNames
         * @param secret
         * @return
         */
        public static String sign(Map<String, String> paramValues, List<String> ignoreParamNames,String secret) {

                try {
                        StringBuilder sb = new StringBuilder();

                        List<String> paramNames = new ArrayList<String>(paramValues.size());

                        paramNames.addAll(paramValues.keySet());

                        if(ignoreParamNames != null && ignoreParamNames.size() > 0){

                                for (String ignoreParamName : ignoreParamNames) {

                                        paramNames.remove(ignoreParamName);

                                }
                        }
                        Collections.sort(paramNames);

                        sb.append(secret);

                        for (String paramName : paramNames) {

                                sb.append(paramName).append(paramValues.get(paramName));

                        }

                        sb.append(secret);

                        byte[] sha1Digest = getSHA1Digest(sb.toString());

                        return byte2hex(sha1Digest);

                } catch (IOException e) {

                        throw new IOException(e);

                }
        }

        public static String utf8Encoding(String value, String sourceCharsetName) {

                try {

                        return new String(value.getBytes(sourceCharsetName), "UTF-8");

                } catch (UnsupportedEncodingException e) {

                        throw new IllegalArgumentException(e);

                }
        }

        private static byte[] getSHA1Digest(String data) throws IOException {

                byte[] bytes = null;

                try {

                        MessageDigest md = MessageDigest.getInstance("SHA-1");

                        bytes = md.digest(data.getBytes("UTF-8"));

                } catch (GeneralSecurityException gse) {

                        throw new IOException(gse.getMessage());

                }

                return bytes;

        }

        private static byte[] getMD5Digest(String data) throws IOException {

                byte[] bytes = null;

                try {

                        MessageDigest md = MessageDigest.getInstance("MD5");

                        bytes = md.digest(data.getBytes("UTF-8"));

                } catch (GeneralSecurityException gse) {

                        throw new IOException(gse.getMessage());

                }

                return bytes;
        }

        /**
         * 二进制转十六进制字符串
         *
         * @param bytes
         * @return
         */
        private static String byte2hex(byte[] bytes) {

                StringBuilder sign = new StringBuilder();

                for (int i = 0; i < bytes.length; i++) {

                        String hex = Integer.toHexString(bytes[i] & 0xFF);

                        if (hex.length() == 1) {

                                sign.append("0");

                        }

                        sign.append(hex.toUpperCase());

                }

                return sign.toString();

        }

        public static String getUUID() {

                UUID uuid = UUID.randomUUID();

                return uuid.toString().toUpperCase();

        }

}

6、三方收到二维火发出的消息,返回接收信息成功

package com.stellarium.controller;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 项目名称:rop-sample
 * 创建时间:2017年06月 10:13
 * 类描述:
 *
 * @author bingli
 * @version 1.0
 */
@Controller
@RequestMapping("/rop")
public class RopController {

    @RequestMapping(value="/thirdpart/wm")
    @ResponseBody
    public String shopBind(HttpServletRequest request) {
        String method = request.getParameter("method");
        String entityId = request.getParameter("entityId");
        // DO business here
        Map<String, Object> map = new HashMap<>();
        map.put("success", Boolean.TRUE);
        map.put("resultCode", "000");
        map.put("message", "操作成功!");
        return JSON.toJSONString(map);
    }
}

PHP实现

实例代码

<?php

//***客又徕-成都徕徕科技出品***

//要求PHP环境:UTF-8编辑,curl库正常开启

//修改数据,直接运行此文件即可,面向对象需求自己修改~

/*
 * $url:访问地址
 * $data:POST推送的数据
 * */
function putPost($url,$data)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_POST, 1);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    $headers=array(
        'Content-type:application/x-www-form-urlencoded;charset="utf-8"'
    );

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $output = curl_exec($ch);

    curl_close($ch);

    $output=json_decode($output,true);
    return $output;

}

//获取签名
function getSignature($params, $secret){

    $str = '';  //待签名字符串

    //先将参数以其参数名的字典序升序进行排序
    ksort($params);

    //遍历排序后的参数数组中的每一个key/value对
    foreach ($params as $k => $v) {
        $temp= $k.$v;
        $str.=$temp;
    }

    //将签名密钥拼接到签名字符串最后面
    $str = $secret.$str.$secret;

    //加密并转成全大些字母
    $res=strtoupper(sha1($str));
    return $res;
}


function test($data,$secret)
{
    $data['sign'] = getSignature($data, $secret);

    //请求数据
    $form_data = http_build_query($data);

    //请求地址
    $url='http://open.2dfire.com/router';

    $res = putPost($url, $form_data);

    return $res;
}


//准备数据

$test = array(

    //改为要求的方法
    'method' => 'XXXXX',

    //改成自己的APP_KEY
    'appKey' => 'XXXXX',

    'v' => '1.0',

    //组装时间戳,单位毫秒
    'timestamp' => round(microtime(true) * 1000),

    //填写自己的商户ID
    'entityId' => 'XXXX',

    'currDate' => date('Ymd', time())
);

//APP_SECRET,改成自己的APP_SECRET

$secret = 'XXXXXXX';

//调用test进行请求
$res=test($test,$secret);

var_dump($res);

//成功示例:array(2) { ["success"]=> bool(true) ["totalRecord"]=> int(0) }
?>

C#实现

1、请求方式

public const string cAPP_KEY = "98ee362b4981c29ff7c932650d4e768c";
public const string cAPP_SECRET = "1f2cc41322bef232098c563457c4f492";
public const string cSESSION_ID = "4ab94c2172d38d06337b54cd4aba342571393a5dd3fad2b7abbd11d840f505281ce49445d082b91cfbe6f0a28af3d774";
public const string cSERVER_URL = "http://open.2dfire-daily.com/open-api/router";
/// <summary>
///  用户登录
/// </summary>
public static void usersLogin()
{
    // 时间戳
    object currenttimemillis = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
    Dictionary<string, string> dicPostData = new Dictionary<string, string>();
    dicPostData.Add("method", "dfire.users.login");
    dicPostData.Add("appKey", cAPP_KEY);
    dicPostData.Add("v", "1.0");
    dicPostData.Add("locale", "zh_CN");
    dicPostData.Add("timestamp", currenttimemillis.ToString());
    dicPostData.Add("userName", "waimai2");
    dicPostData.Add("password", RopUtils.CreateMD5Hash("123456", "utf-8"));
    // 对请求参数列表进行签名
    string strSign = RopUtils.sign(dicPostData, cAPP_SECRET);
    dicPostData.Add("sign", strSign);
    string strPostData = string.Format("method={0}&appKey={1}&v={2}&locale={3}&timestamp={4}&userName={5}&password={6}&sign={7}",
        dicPostData["method"],
        dicPostData["appKey"],
        dicPostData["v"],
        dicPostData["locale"],
        dicPostData["timestamp"],
        dicPostData["userName"],
        dicPostData["password"],
        dicPostData["sign"]);
    string strResponse = httpPost(strPostData);
    Console.WriteLine(strResponse);
}
/// <summary>
///  店铺外部关系查询
/// </summary>
public static void shopExternalSearch()
{
    // 时间戳
    object currenttimemillis = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
    Dictionary<string, string> dicPostData = new Dictionary<string, string>();
    dicPostData.Add("method", "dfire.shop.external.search");
    dicPostData.Add("appKey", cAPP_KEY);
    dicPostData.Add("v", "1.0");
    dicPostData.Add("locale", "zh_CN");
    dicPostData.Add("timestamp", currenttimemillis.ToString());
    // 对请求参数列表进行签名
    string strSign = RopUtils.sign(dicPostData, cAPP_SECRET);
    dicPostData.Add("sign", strSign);
    dicPostData.Add("sessionId", cSESSION_ID);
    string strPostData = string.Format("method={0}&appKey={1}&v={2}&locale={3}&timestamp={4}&sign={5}&sessionId={6}",
        dicPostData["method"],
        dicPostData["appKey"],
        dicPostData["v"],
        dicPostData["locale"],
        dicPostData["timestamp"],
        dicPostData["sign"],
        dicPostData["sessionId"]);
    string strResponse = httpPost(strPostData);
    Console.WriteLine(strResponse);
}
/// <summary>
///  商品类目接口
/// </summary>
public static void kindmenuQuery()
{
    // 时间戳
    object currenttimemillis = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
    Dictionary<string, string> dicPostData = new Dictionary<string, string>();
    dicPostData.Add("method", "dfire.kindmenu.query");
    dicPostData.Add("appKey", cAPP_KEY);
    dicPostData.Add("v", "1.0");
    dicPostData.Add("locale", "zh_CN");
    dicPostData.Add("timestamp", currenttimemillis.ToString());
    dicPostData.Add("entityId", "99180959");
    // 对请求参数列表进行签名
    string strSign = RopUtils.sign(dicPostData, cAPP_SECRET);
    dicPostData.Add("sign", strSign);
    dicPostData.Add("sessionId", cSESSION_ID);
    string strPostData = string.Format("method={0}&appKey={1}&v={2}&locale={3}&timestamp={4}&entityId={5}&sign={6}&sessionId={7}",
        dicPostData["method"],
        dicPostData["appKey"],
        dicPostData["v"],
        dicPostData["locale"],
        dicPostData["timestamp"],
        dicPostData["entityId"],
        dicPostData["sign"],
        dicPostData["sessionId"]);
    string strResponse = httpPost(strPostData);
    Console.WriteLine(strResponse);
}
/// <summary>
/// 模拟http发送post方法
/// </summary>
/// <param name="strPostData">请求参数</param>
private static string httpPost(string strPostData)
{
    Encoding requestCoding = Encoding.UTF8;
    Encoding responseCoding = Encoding.UTF8;
    try
    {
        // 参数写入byte数组
        byte[] byteArray = requestCoding.GetBytes(strPostData);
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(cSERVER_URL);
        webRequest.Method = "POST";
        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.ContentLength = byteArray.Length;
        webRequest.KeepAlive = true;
        Stream newStream = webRequest.GetRequestStream();
        newStream.Write(byteArray, 0, byteArray.Length);
        newStream.Close();
        // 接收返回信息:
        HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), responseCoding);
        return reader.ReadToEnd();
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
}

2、签名部分

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace LoginServiceConsole
{
    public static class RopUtils
    {
        /// <summary>
        /// 对传入字符串进行MD5加密
        /// </summary>
        /// <param name="strInput">传入字符串</param>
        /// <param name="strCharsetName">文字编码</param>
        /// <returns></returns>
        public static string CreateMD5Hash(string strInput, string strCharsetName)
        {
            // Use input string to calculate MD5 hash
            MD5 md5 = MD5.Create();
            byte[] inputBytes = Encoding.GetEncoding(strCharsetName).GetBytes(strInput);
            byte[] hashBytes = md5.ComputeHash(inputBytes);

            // Convert the byte array to hexadecimal string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("x2"));
                // To force the hex string to lower-case letters instead of
                // upper-case, use he following line instead:
                // sb.Append(hashBytes[i].ToString("x2"));
            }
            return sb.ToString();
        }

       /// <summary>
       /// 对请求参数列表进行签名
       /// </summary>
       /// <param name="dicParamValues">参数列表</param>
       /// <param name="strSecret">秘钥</param>
       /// <returns></returns>
       public static string sign(Dictionary<string, string> dicParamValues, string strSecret)
       {
           try
           {
               StringBuilder sb = new StringBuilder();
               //ArrayList paramNames = new ArrayList();
               string[] paramNames = dicParamValues.Keys.ToArray();
               //paramNames.AddRange(dicParamValues.Keys);
               // 按key进行字典升序排列
               //paramNames.Sort(StringComparison.Ordinal);
               //string[] s = { "a", "A", "ab", "aB", "Ab", "AB", "b", "B" };
               Array.Sort(paramNames, (a, b) => string.CompareOrdinal(a, b));
               // 使用secret对keyvalue按首尾进行拼接
               sb.Append(strSecret);
               foreach (string paramName in paramNames)
               {
                   sb.Append(paramName).Append(dicParamValues[paramName]);
               }
               sb.Append(strSecret);
               return getSHA1Digest(sb.ToString());
           }
           catch (IOException e)
           {
               return "";
           }
       }

        /// <summary>
        /// 使用SHA1对secret拼接好的字符串进行加密
        /// </summary>
        /// <param name="strData"></param>
        /// <returns></returns>
        public static string getSHA1Digest(string strData)
        {
            StringBuilder sb = new StringBuilder();
            try
            {
                SHA1 sha1 = new SHA1CryptoServiceProvider();
                byte[] bytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(strData));
                foreach (byte b in bytes)
                {
                    // 将转换之后的字符串字母转成大写
                    sb.Append(b.ToString("X2"));
                }
            }
            catch (InvalidOperationException gse)
            {
                throw new IOException(gse.Message);
            }
            return sb.ToString();
        }
    }
}