饿了么 openapi demo

http://merchant.openapi.eleme.io/merchant.html#id215

class Program
    {
        static void Main(string[] args)
        {
            EleMakSign.SignValue.Add("consumer_key", "0170804777");
            //EleMakSign.SignValue.Add("consumer_secret", "87217cb263701f90316236c4df00d9352fb1da76");
            EleMakSign.SignValue.Add("timestamp", "1466412691398");
            //EleMakSign.SignValue.Add("food_id", "20385638");
            //EleMakSign.SignValue.Add("name", "肥牛套餐 + 可乐");
            //EleMakSign.SignValue.Add("description", "精选五星肥牛,御用厨师:李大胖,倾情烹制");
            //EleMakSign.SignValue.Add("stock", 1000);
            //Root r = new Root() { key1 = "value1", key2 = "value2" };

            //EleMakSign.SignValue.Add("json", JsonConvert.SerializeObject(r));

            string val=EleMakSign.genMakSig("http://v2.openapi.ele.me/restaurant/62028381/", EleMakSign.SignValue, EleMeConfig.consumer_secret);
            Console.Write(val);



            //获取订单
            //
            string requrl = "http://v2.openapi.ele.me/order/new/";

            EleMakSign.SignValue.Clear();
            string consumer_key="0170804777";
            EleMakSign.SignValue.Add("consumer_key", consumer_key);
            string timsp=ElemeMakSignHelper.GetTimeStamp();
            EleMakSign.SignValue.Add("timestamp",timsp );
            string consumer_secret="87217cb263701f90316236c4df00d9352fb1da76";            
             string restaurant_id="62028381";
            EleMakSign.SignValue.Add("restaurant_id", restaurant_id);
            string sig=EleMakSign.genMakSig(requrl, EleMakSign.SignValue, consumer_secret);

            EleMakSign.SignValue.Clear();
            EleMakSign.SignValue.Add("consumer_key", consumer_key);
            EleMakSign.SignValue.Add("timestamp",timsp );
                 EleMakSign.SignValue.Add("restaurant_id", restaurant_id);
                 EleMakSign.SignValue.Add("sig", sig);

            string str = ElemeMakSignHelper.concatParams(EleMakSign.SignValue);
            str = requrl + "?" + str;
            string result=HttpUtilsHelper.HttpGet(str,"");
            Console.Write(result);
            Console.ReadKey();
            //字符串a
            //字符串b
            //字符串c


        }
    }
View Code
/// <summary>
    /// ele  签名
    /// </summary>
    public class EleMakSign
    {

        //对参数进行排序得到 字符串A
        //将所有参数(sig除外)按照参数名的字母顺序排序,并用 & 连接:
        //consumer_key=7284397484&timestamp=1374908054

        public static SortedDictionary<string, object> SignValue = new SortedDictionary<string, object>();


        /**
        * 设置某个字段的值
        * @param key 字段名
         * @param value 字段值
        */
        public void SetValue(string key, object value)
        {
            SignValue[key] = value;
        }

        /**
        * 根据字段名获取某个字段的值
        * @param key 字段名
         * @return key对应的字段值
        */
        public object GetValue(string key)
        {
            object o = null;
            SignValue.TryGetValue(key, out o);
            return o;
        }

        /**
         * 判断某个字段是否已设置
         * @param key 字段名
         * @return 若字段key已被设置,则返回true,否则返回false
         */
        public bool IsSet(string key)
        {
            object o = null;
            SignValue.TryGetValue(key, out o);
            if (null != o)
                return true;
            else
                return false;
        }


        public static string sortedToString(SortedDictionary<string, object> SignValue, string key)
        {
            string str = "";
            foreach (var item in SignValue)
                str += item + key;
            return str;
        }


        public static string genMakSig(string pathUrl, SortedDictionary<string, object> dics,
                                    string consumerSecret)
        {
            string str = ElemeMakSignHelper.concatParams(dics);
            str = pathUrl + "?" + str + consumerSecret;
            System.Security.Cryptography.SHA1 sha1 = System.Security.Cryptography.SHA1.Create();
            return ElemeMakSignHelper.byte2hex(sha1.ComputeHash(Encoding.UTF8.GetBytes(ElemeMakSignHelper.byte2hex(Encoding.UTF8.GetBytes(str)))));
        }

    }
elemksign
/// <summary>
    /// 饿了么商家信息配置
    /// consumer_key: 0170804777
    ///consumer_secret: 87217cb263701f90316236c4df00d9352fb1da76
    ///restaurant_id: 62028381
    ///restaurant_name: 饿了么开放平台测试
    ///餐厅下单测试地址: http://r.ele.me/openapi-test
    ///关于 POST / PUT 请求头中 contennt_type 的说明:
    ///除特别声明需要指定的请求头(如图片接口的图片内容参数 file,使用 multipart/form-data )之外,
    ///其他接口默认使用 application/x-www-form-urlencoded
    /// </summary>
    public static class EleMeConfig
    {
        public static string comsumer_key = "0170804777";
        public static string consumer_secret = "87217cb263701f90316236c4df00d9352fb1da76";
        public static int restaurant_id = 62028381;
        public static string reqBaseUrl = "http://v2.openapi.ele.me/restaurant/62028381/";
    }
饿了么商家信息配置
public static class ElemeMakSignHelper
    {

        public static string concatParams(SortedDictionary<string, object> dics)
        {
            string str = "";
            foreach (var key in dics.Keys)
            {
                object tval = "";
                if (dics.TryGetValue(key, out tval))
                {
                    //string tkey = EleMakSign.UrlEncode(key);
                    //string ttval = EleMakSign.UrlEncode(tval.ToString());
                    string tkey = key;
                    string ttval = tval.ToString();
                    str += "&" + tkey + "=" + ttval;
                }
            }
            return str.Substring(1);
        }

        public static string byte2hex(byte[] b)
        {
            StringBuilder enText = new StringBuilder();
            int i;
            for (int offset = 0; offset < b.Length; offset++)
            {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    enText.Append("0");
                enText.Append(ElemeMakSignHelper.toHexString(i));
            }
            return enText.ToString();
        }

        private static string toHexString(int i)
        {
            return ElemeMakSignHelper.toUnsignedString(i, 4);
        }
        private static String toUnsignedString(int i, int shift)
        {
            char[] buf = new char[32];
            int charPos = 32;
            int radix = 1 << shift;
            int mask = radix - 1;
            do
            {
                buf[--charPos] = digits[i & mask];
                i = foo(i, shift);
            } while (i != 0);

            return new String(buf, charPos, (32 - charPos));
        }
        public static int foo(int x, int y)
        {
            int mask = 0x7fffffff; //Integer.MAX_VALUE
            for (int i = 0; i < y; i++)
            {
                x >>= 1;
                x &= mask;
            }
            return x;
        }
        public static char[] digits = {
            '0' , '1' , '2' , '3' , '4' , '5' ,
            '6' , '7' , '8' , '9' , 'a' , 'b' ,
            'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
            'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
            'o' , 'p' , 'q' , 'r' , 's' , 't' ,
            'u' , 'v' , 'w' , 'x' , 'y' , 'z'
            };


        /// <summary>  
        /// 获取时间戳  
        /// </summary>  
        /// <returns></returns>  
        public static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }  
    }
ElemeMakSignHelper
/// <summary>
    /// http get post helper class
    /// </summary>
    public static class HttpUtilsHelper
    {
        public static string HttpGet(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        public static string HttpPost(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/json;charset=UTF-8";
            string paraUrlCoded = postDataStr;
            byte[] payload;
            payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
            request.ContentLength = payload.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(payload, 0, payload.Length);
            writer.Close();
            System.Net.HttpWebResponse response;
            response = (System.Net.HttpWebResponse)request.GetResponse();
            System.IO.Stream s;
            s = response.GetResponseStream();
            string StrDate = "";
            string strValue = "";
            StreamReader Reader = new StreamReader(s, Encoding.UTF8);
            while ((StrDate = Reader.ReadLine()) != null)
            {
                strValue += StrDate + "\r\n";
            }
            return strValue;
        }
    }
HttpUtilsHelper

 完整代码在:http://download.csdn.net/detail/u010683837/9555239

转载于:https://my.oschina.net/jiemoxiaodi/blog/848213

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值