码迷,mamicode.com
首页 > 微信 > 详细

微信支付 jsapi接口

时间:2014-12-08 15:07:17      阅读:733      评论:0      收藏:0      [点我收藏+]

标签:des   blog   http   io   ar   os   使用   sp   for   

        /// <summary>
        /// 微信支付成功,返回信息
        /// </summary>
        /// <returns></returns>
        public void WxZhifuInfo()
        {
            string post = "";
            HttpRequestBase request = Request;
            using (System.IO.Stream stream = request.InputStream)
            {
                Byte[] postBytes = new Byte[stream.Length];
                stream.Read(postBytes, 0, (Int32)stream.Length);
              post =  System.Text.Encoding.UTF8.GetString(postBytes);
            }

            writeLogs.writelog("支付成功,返回信息:" + post);
            Response.Write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
                               // "<return_msg><![CDATA[]]></return_msg></xml>");
            Response.End();
        }
    /// <summary>
    /// 提交微信支付
    /// </summary>
    /// <param name="orderid">订单编号</param>
    /// <param name="title">商品标题</param>
    /// <param name="openid">用户编号</param>
    /// <param name="weiId">公众号</param>
    /// <returns></returns>
        public string WxZhifuApi(string orderid,string title,string openid,string weiId)
        {
            try {

                SignCode sign = new SignCode();
                //获取商户的配置参数
                string sql = "select * from pay_info where Enable=1";//必须保证是一条数据否则默认失败
                DataTable dt = SQLiteDBHelper.GetDataTable(sql, weiId);
                if (dt.Rows.Count > 0)//查看是否存在数据
                {
                    sign.appid = dt.Rows[0]["appid"].ToString();
                    sign.mch_id = dt.Rows[0]["Mchid"].ToString();
                    Setkey = dt.Rows[0]["KeyValue"].ToString();
                }
                else {
                    writeLogs.writelog("查询商户配置参数错误,请检查参数是否正确");   
                    return "{\"errcode\":\"3\"}";//商户未设置支付参数
                }
                string Time = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
                sign.body = title;
                sign.nonce_str = "abcdefghijklmnopqrstuvwxyzqqqqqq";//随机数固定不变
                sign.openid = openid; //"oaR7LjvZ5qFcoD0q4_zAhhTruqwY";
                sign.out_trade_no = orderid; //"D"+Time;
                sign.spbill_create_ip = "127.0.0.1";
                //使用订单编号查询订单总价格
                sql = "select * from order_info where orderid="+orderid+" and openid=‘"+openid+"‘  ";
                dt = SQLiteDBHelper.GetDataTable(sql, weiId);
                if (dt.Rows.Count > 0)
                {

                    sign.total_fee = Convert.ToString( float.Parse(dt.Rows[0]["Receivables"].ToString()) * 100); //测试阶段价格写1 ,单位:分    
                }
                else {
                    writeLogs.writelog("查询订单编号价格错误");
                    return "{\"errcode\":\"4\"}";//订单编号错误或订单不存在
                }
                
                sign.notify_url = string.Format("http://shop.bcowei.com/Template/WxZhifuInfo");// string.Format("shop.bcowei.com/Template/orderpay?weiId={0}&openid={1}&pay={2}&orderId={3}",weiId,openid,"1",orderid);//接受微信支付成功信息
                string code = WxSign(sign);
                string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
                prepay p = new prepay();
                string result = System.Web.PostAndGet.PostWebRequest(url, code, "utf-8");
                XmlSerializer xml = new XmlSerializer(typeof(prepay));
                StringReader reader = new StringReader(result);
                prepay prepay = xml.Deserialize(reader) as prepay;
                if (prepay.result_code == null || prepay.result_code == "")
                {
                    writeLogs.writelog("prepay_id获取失败,检查参数配置是否正确,参数内容:"+code);
                    //Response.Redirect(string.Format("/ordererror/Template?weiId={0}&openid={1}&errcode=11",weiId,openid));
                    return "{\"errcode\":\"1\"}";
                }
                string prepayid =  string.Format("prepay_id={0}", prepay.prepay_id);
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("appId", sign.appid);
                dic.Add("timeStamp",Time);
                dic.Add("nonceStr",sign.nonce_str);
                dic.Add("package", prepayid);
                dic.Add("signType", "MD5");
               //Template/index1?appid={0}&timeStamp={1}&nonceStr={2}&package={3}&signType={4}&paySign={5}",sign.appid,Time,sign.nonce_str,prepayid,"MD5",WxSignCreate(dic)));
                ViewBag.appid = sign.appid;
                ViewBag.time = Time;
                ViewBag.noncestr = sign.nonce_str;
                ViewBag.package = prepayid;
                ViewBag.signType = "MD5";
                ViewBag.paySign = WxSignCreate(dic);
                ViewBag.weiId = weiId;
                ViewBag.openid = openid;
                ViewBag.orderid = orderid;
                return "{\"errcode\":\"0\","+
                       "\"appid\":\"" + sign.appid + "\","+
                       "\"time\":\"" + Time + "\","+
                       "\"noncestr\":\"" + sign.nonce_str + "\","+
                       "\"package\":\""+prepayid+"\","+
                       "\"signType\":\"MD5\","+
                       "\"paySign\":\""+WxSignCreate(dic)+"\""+
                       "}";
                
                   
            }
            catch (Exception e)
            {
               // Response.Redirect(string.Format("/ordererror/Template?weiId={0}&openid={1}&errcode=15", weiId, openid));
                return "{\"errcode\":\"1\"}";
            }
           
        }
        /// <summary>
        /// key值
        /// </summary>
        /// <returns></returns>
        public static string Setkey { get; set; }
        /// <summary>
        /// 生成签名
        /// </summary>
        /// <param name="body">商品描述</param>
        /// <param name="openid">用户标识</param>
        /// <param name="out_trade_no">订单编号</param>
        /// <param name="total_fee">价钱</param>
        /// <param name="notify_url">成功跳转路径</param>
        /// <param name="spbill_create_ip">设备IP</param>
        /// <returns></returns>
        public string WxSign(SignCode code)
        {
            //string appid,string mch_id,string nonce_str,string body, string openid, string out_trade_no, string total_fee, string notify_url, string spbill_create_ip
            Dictionary<string, string> sign = new Dictionary<string, string>();//字典建值对
            try {

                sign.Add("appid",code.appid);//公众号标识,1
                sign.Add("body", code.body);//商品描述,0
                sign.Add("mch_id", code.mch_id);//商户编号,1
                sign.Add("nonce_str",code.nonce_str);//随机字符串,1
                sign.Add("openid", code.openid);//微信用户编号,0
                sign.Add("out_trade_no", code.out_trade_no);//订单编号,0
                sign.Add("spbill_create_ip", code.spbill_create_ip);//设备IP,0
                sign.Add("total_fee", code.total_fee);//价钱 单位:分,0
                sign.Add("notify_url", code.notify_url);//请求成功跳转地址,0
                sign.Add("trade_type", "JSAPI");//支付方式,1
                sign.Add("sign", WxSignCreate(sign));//签名

            
            }
            catch (Exception e)
            {
                writeLogs.writelog("参数键值对异常:"+e.Message);
                return "参数键值对异常:" + e.Message;
            }
            string ddd = WxXml(sign);
            return WxXml(sign);//参数转化xml
        }
        public class getPay {
            public string appId { get; set; }
            public string timeStamp { get; set; }
            public string nonceStr { get; set; }
            public string package { get; set; }
            public string signType { get; set; }
            public string paySign { get; set; }
        }
        /// <summary>
        /// 签名参数
        /// </summary>
        public class SignCode {
            public string appid { get; set; }
            public string mch_id { get; set; }
            public string nonce_str { get; set; }
            public string body { get; set; }
            public string openid { get; set; }
            public string out_trade_no { get; set; }
            public string total_fee { get; set; }
            public string notify_url { get; set; }
            public string spbill_create_ip { get; set; }
        }
        /// <summary>
        /// 转换xml格式
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        public string WxXml(Dictionary<string,string> dic)
        {
            StringBuilder sb = new StringBuilder();
            try {
                sb.Append("<xml>");
                foreach (var key in dic.Keys)
                { 
                    //<appid>wx2421b1c4370ec43b</appid
                    sb.Append("<"+key+">"+dic[key]+"</"+key+">");
                }
                sb.Append("</xml>");
            }
            catch (Exception e)
            {
                writeLogs.writelog("参数转换xml异常:"+e.Message);
                return null;
            }
            return sb.ToString();
        }
        /// <summary>
        /// 拼接签名生成
        /// </summary>
        /// <param name="Sign"></param>
        /// <returns></returns>
        public string WxSignCreate(Dictionary<string,string> Sign)
        {
            string create = "";//拼接字符串
            try {
              
                var result = from i in Sign orderby i.Key select i;
                foreach(KeyValuePair<string,string> pair in result)
                {
                    string key = pair.Key;
                    string value = pair.Value;
                    create += key + "=" + value + "&";
                }
                create = create.TrimEnd(‘&‘);
                
            }
            catch (Exception e)
            {
                writeLogs.writelog("签名拼接异常:"+e.Message);
                return "签名拼接异常:" + e.Message;
            }
            return WxSignMD5(create);
        }
        /// <summary>
        /// 请求签名MD5
        /// </summary>
        /// <param name="sign"></param>
        /// <returns></returns>
        public string WxSignMD5(string sign)
        {
            string Signstr = sign + "&key=" + Setkey;
                return MD5(Signstr).ToUpper();//MD5转换
        }
        /// <summary>
        /// 签名MD5
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String MD5(String s)
        {
            char[] hexDigits = { ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘,
					‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘ };
            try
            {

                byte[] btInput = System.Text.Encoding.UTF8.GetBytes(s);
                // 获得MD5摘要算法的 MessageDigest 对象
              System.Security.Cryptography.MD5 mdInst = System.Security.Cryptography.MD5.Create();
                // 使用指定的字节更新摘要
                mdInst.ComputeHash(btInput);
                // 获得密文
                byte[] md = mdInst.Hash;
                // 把密文转换成十六进制的字符串形式
                int j = md.Length;
                char[] str = new char[j * 2];
                int k = 0;
                for (int i = 0; i < j; i++)
                {
                    byte byte0 = md[i];
                    str[k++] = hexDigits[(int)(((byte)byte0) >> 4) & 0xf];
                    str[k++] = hexDigits[byte0 & 0xf];
                }
                return new string(str);//编码转换
            }
            catch (Exception e)
            {
                writeLogs.writelog("调用签名md5异常:"+e.Message);
                return null;
            }
        }

  

微信支付 jsapi接口

标签:des   blog   http   io   ar   os   使用   sp   for   

原文地址:http://www.cnblogs.com/xuemykisskui/p/4150950.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!