Exemple #1
0
 /// <summary>
 /// 必须传入Debug,Url,可选传入:WeChatPublic
 /// </summary>
 /// <param name="param"></param>
 /// <returns></returns>
 public string CreateWxConfig(WeChatParam param)
 {
     try
     {
         var noncestr    = PayUtil.GetNoncestr();
         var timestamp   = PayUtil.GetTimestamp();
         var jsapiTicket = Token.GetJsapiTicket(param);
         var appId       = GetConfig.GetAppid(param);
         var packageReq  = new RequestHandler();
         packageReq.SetParameter("noncestr", noncestr);
         packageReq.SetParameter("jsapi_ticket", jsapiTicket);
         packageReq.SetParameter("timestamp", timestamp);
         packageReq.SetParameter("url", param.Url);
         var signature = packageReq.CreateSHA1Sign();
         // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
         // 必填,公众号的唯一标识
         // 必填,生成签名的时间戳
         // 必填,生成签名的随机串
         // 必填,签名,见附录1
         // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
         var result = "wx.config({debug:" + (param.Debug ? "true" : "false") + ", appId: '" + appId + "', timestamp: " + timestamp + ", nonceStr: '" + noncestr + "', signature: '" + signature + "',jsApiList: ['checkJsApi','onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','hideMenuItems','showMenuItems','hideAllNonBaseMenuItem','showAllNonBaseMenuItem','translateVoice','startRecord','stopRecord','onRecordEnd','playVoice','pauseVoice','stopVoice','uploadVoice','downloadVoice','chooseImage','previewImage','uploadImage','downloadImage','getNetworkType','openLocation','getLocation','hideOptionMenu','showOptionMenu','closeWindow','scanQRCode','chooseWXPay','openProductSpecificView','addCard','chooseCard','openCard'] });";//'checkJsApi',
         return(result);
     }
     catch (Exception ex)
     {
         return("var error='" + ex.Message.Replace("\r\n", "").Replace("\n", "").Replace("\t", "").Replace("<br>", "").Replace("'", "\"") + "';");
     }
 }
Exemple #2
0
        /// <summary>
        /// 传入 OpenId,订单Id,金额(分),过期时间(20141010121314),商品名称。
        /// </summary>
        /// <returns></returns>
        public static string CreateJSAPIPayJson(PayParam param)
        {
            if (param.TotalFee == null || string.IsNullOrWhiteSpace(param.ProductName) || string.IsNullOrWhiteSpace(param.OrderNumber) || string.IsNullOrWhiteSpace(param.OpenId) || string.IsNullOrWhiteSpace(param.TimeExpire))
            {
                return("参数错误");
            }
            param.TradeType = EnumHelper.TradeType.JSAPI;
            var result = GetUnifiedOrder(param);
            //LogHelper.WriteLog("aa_", "GetUnifiedOrder后的值是:" + result);
            var xe = XElement.Parse(result, LoadOptions.SetLineInfo);

#warning 这里暂时使用了 redis的Common
            try
            {
                var prepayId = xe.GetElement("prepay_id").Value;
                var payReq   = new RequestHandler();
                payReq.SetKey(GetConfig.GetKey(param));
                payReq.SetParameter("appId", GetConfig.GetAppid(param));
                payReq.SetParameter("timeStamp", PayUtil.GetTimestamp());
                payReq.SetParameter("nonceStr", PayUtil.GetNoncestr());
                payReq.SetParameter("package", "prepay_id=" + prepayId);
                payReq.SetParameter("signType", "MD5");
                //创建签名
                payReq.SetParameter("paySign", payReq.CreateMd5Sign());
                var payReqXml  = payReq.ParseXml();
                var payReqJson = payReq.ParseJson();
                return(payReqJson);
            }
            catch (Exception)
            {
                var returnCode = xe.GetElement("return_code").Value;
                var returnMsg  = xe.GetElement("return_msg").Value;
                return("{Error:'" + returnCode + returnMsg + "'}");
            }
        }
Exemple #3
0
        /// <summary>
        ///
        /// </summary>
        public static string GetJsapiTicket(WeChatParam param)
        {
            var appId = GetConfig.GetAppid(param);

            if (!AccessTicketsCache.ContainsKey(appId) || AccessTicketsCache[appId] == null ||
                AccessTicketsCache[appId].ExpireTime < DateTime.Now)
            {
                var result = HttpHelper.Get <TokenResult>(ApiList.GetticketUrl, new HttpParam
                {
                    { "access_token", GetAccessToken(param) },
                    { "type", "jsapi" }
                });
                if (result.errmsg != "ok")
                {
                    throw new WxException(result.errcode, result.errmsg);
                }

                AccessTicketsCache[appId] = new TokenCache
                {
                    JsapiTicket = result.ticket,
                    ExpireTime  = DateTime.Now.AddSeconds(result.expires_in - 3)
                };
            }
            return(AccessTicketsCache[appId].JsapiTicket);
        }
Exemple #4
0
        /// <summary>
        /// 获取access_token。会缓存,过期后自动重新获取新的token。
        /// </summary>
        public static string GetAccessToken(WeChatParam param = null)
        {
            var appId  = GetConfig.GetAppid(param);
            var secret = GetConfig.GetSecret(param);

            if (!AccessTokensCache.ContainsKey(appId) || AccessTokensCache[appId] == null ||
                AccessTokensCache[appId].ExpireTime < DateTime.Now)
            {
                var result = HttpHelper.Get <TokenResult>(ApiList.GetTokenUrl, new HttpParam
                {
                    { "grant_type", "client_credential" },
                    { "appid", appId },
                    { "secret", secret }
                });
                if (!result.IsSuccess)
                {
                    throw new WxException(result.errcode, result.errmsg);
                }
                AccessTokensCache[appId] = new TokenCache
                {
                    AccessToken = result.access_token,
                    ExpireTime  = DateTime.Now.AddSeconds(result.expires_in - 60)
                };
            }
            return(AccessTokensCache[appId].AccessToken);
        }
Exemple #5
0
        /// <summary>
        /// 传入Code
        /// </summary>
        public static Dictionary <string, string> GetOauth2AccessToken(UserParam param)
        {
            var param2 = new HttpParam()
            {
                { "appid", GetConfig.GetAppid(param) },
                { "secret", GetConfig.GetSecret(param) },
                { "code", param.Code },
                { "grant_type", "authorization_code" }
            };
            var dic = HttpHelper.Get <Dictionary <string, string> >(ApiList.GetOauth2AccessTokenUrl, param2);

            return(dic);
        }
Exemple #6
0
        /// <summary>
        /// 传入ProductName,OrderNumber,TotalFee,TimeExpire,OpenId(可选),TradeType,NotifyUrl(可选)
        /// </summary>
        /// <param name="param"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public string GetUnifiedOrder(PayParam param = null, HttpContextBase context = null)
        {
            if (param.TotalFee == null || string.IsNullOrWhiteSpace(param.ProductName) || string.IsNullOrWhiteSpace(param.OrderNumber) || string.IsNullOrWhiteSpace(param.TimeExpire) || param.TradeType == null)
            {
                return("参数错误");
            }
            var req = new RequestHandler(context);

            req.SetKey(GetConfig.GetKey(param));
            req.SetParameter("appid", GetConfig.GetAppid(param));
            req.SetParameter("mch_id", GetConfig.GetMchId(param));
            req.SetParameter("nonce_str", GetNoncestr());
            req.SetParameter("body", param.ProductName);
            req.SetParameter("out_trade_no", param.OrderNumber);
            req.SetParameter("total_fee", param.TotalFee.ToString());
            req.SetParameter("spbill_create_ip", IPHelper.GetVisitorIP());
            req.SetParameter("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            req.SetParameter("time_expire", param.TimeExpire);
            req.SetParameter("notify_url",
                             string.IsNullOrWhiteSpace(param.NotifyUrl) ? GetConfig.GetNotify(param) : param.NotifyUrl);
            req.SetParameter("trade_type", param.TradeType.ToString());
            if (!string.IsNullOrWhiteSpace(param.OpenId))
            {
                req.SetParameter("openid", param.OpenId);
            }
            req.SetParameter("sign", req.CreateMd5Sign());

            var reqXml = req.ParseXml();
            //LogHelper.WriteLog("aa_", "reqXml的值是:" + reqXml);
            var http = new HttpUtil();

            http.SetCharset(context == null
                ? HttpContext.Current.Request.ContentEncoding.BodyName
                : context.Request.ContentEncoding.BodyName);
            var result = http.Send(reqXml, ApiList.UnifiedOrderUrl);

            return(result);
        }
Exemple #7
0
        /// <summary>
        /// billDate格式 20141212
        /// </summary>
        /// <param name="context"></param>
        /// <param name="billDate"></param>
        /// <returns></returns>
        public static BaseResult DownloadBill(string billDate, WeChatParam param)
        {
            var packageReq = new RequestHandler();

            packageReq.SetKey(GetConfig.GetKey(param));
            packageReq.SetParameter("appid", GetConfig.GetAppid(param));
            packageReq.SetParameter("mch_id", GetConfig.GetMchId(param));
            packageReq.SetParameter("nonce_str", GetNoncestr());
            packageReq.SetParameter("bill_date", billDate);
            packageReq.SetParameter("bill_type", "ALL");
            packageReq.SetParameter("sign", packageReq.CreateMd5Sign());
            var reqXml     = packageReq.ParseXml();
            var httpClient = new HttpUtil();

            httpClient.SetCharset(HttpContext.Current.Request.ContentEncoding.BodyName);
            var result = httpClient.Send(reqXml, ApiList.DownloadBillUrl);

            try
            {
                var xe        = XElement.Parse(result, LoadOptions.SetLineInfo);
                var reResult1 = xe.GetElement("return_code") == null ? "" : xe.GetElement("return_code").Value;
                var reResult2 = xe.GetElement("return_msg") == null ? "" : xe.GetElement("return_msg").Value;
                return(new BaseResult()
                {
                    IsSuccess = false, Data = "", Message = reResult1 + "_" + reResult2
                });
            }
            catch (Exception)
            {
                var list   = new List <Bill>();
                var myList = result.Replace("\r\n", "|").Split('|').Skip(1).ToList <string>();
                myList.RemoveAt(myList.Count() - 1);
                myList.RemoveAt(myList.Count() - 1);
                myList.RemoveAt(myList.Count() - 1);
                string[] arr;
                foreach (var str in myList)
                {
                    arr = str.Replace("`", "").Split(',');
                    #region 赋值
                    list.Add(new Bill()
                    {
                        交易时间     = arr[0],
                        公众账号ID   = arr[1],
                        商户号      = arr[2],
                        子商户号     = arr[3],
                        设备号      = arr[4],
                        微信订单号    = arr[5],
                        商户订单号    = arr[6],
                        用户标识     = arr[7],
                        交易类型     = arr[8],
                        交易状态     = arr[9],
                        付款银行     = arr[10],
                        货币种类     = arr[11],
                        总金额      = arr[12],
                        企业红包金额   = arr[13],
                        微信退款单号   = arr[14],
                        商户退款单号   = arr[15],
                        退款金额     = arr[16],
                        企业红包退款金额 = arr[17],
                        退款类型     = arr[18],
                        退款状态     = arr[19],
                        商品名称     = arr[20],
                        商户数据包    = arr[21],
                        手续费      = arr[22],
                        费率       = arr[23]
                    });
                    #endregion
                }
                return(new BaseResult()
                {
                    IsSuccess = true, Data = list
                });
            }
        }
Exemple #8
0
        /// <summary>
        /// 传入订单号OrderNumber,RefundNumber,总金额total_fee(分),RefundFee退款金额(分),
        /// </summary>
        /// <param name="context"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static BaseResult Refund(PayParam param)
        {
            if (param.TotalFee == null || param.RefundFee == null || string.IsNullOrWhiteSpace(param.OrderNumber) || string.IsNullOrWhiteSpace(param.RefundNumber))
            {
                return(new BaseResult()
                {
                    IsSuccess = false, Message = "参数错误!"
                });
            }
            #region 财付通退款,已OK
            //var packageReq = new RequestHandler(context);
            //packageReq.SetKey(Key);
            //packageReq.SetParameter("partner", "1225604801");
            //packageReq.SetParameter("out_trade_no", param.OrderNumber);
            //packageReq.SetParameter("out_refund_no", param.OrderNumber);
            //packageReq.SetParameter("total_fee", param.TotalFee.Value.ToString(CultureInfo.InvariantCulture));
            //packageReq.SetParameter("refund_fee", param.RefundFee.Value.ToString(CultureInfo.InvariantCulture));
            //packageReq.SetParameter("op_user_id", "1225604801");
            //packageReq.SetParameter("op_user_passwd", "111111");
            //packageReq.SetParameter("sign", packageReq.CreateSign());
            //var httpClient = new HttpUtil();
            ////httpClient.SetCharset(context.Request.ContentEncoding.BodyName);
            ////这里很神奇,必须要用 GB2312编码,不能通过 context.Request.ContentEncoding.BodyName获取编码
            //httpClient.SetCharset("gb2312");
            //httpClient.SetCertInfo(WeChatCertPath, WeChatCertPwd);
            //var reqXml = packageReq.GetRequestURL();
            //var result = httpClient.Send(reqXml, "https://mch.tenpay.com/refundapi/gateway/refund.xml");
            //var xe = XElement.Parse(result, LoadOptions.SetLineInfo);
            //return new BaseResult() { IsSuccess = false };
            #endregion

            #region 微信退款
            var packageReq = new RequestHandler();
            packageReq.SetKey(GetConfig.GetKey(param));
            packageReq.SetParameter("appid", GetConfig.GetAppid(param));
            packageReq.SetParameter("mch_id", GetConfig.GetMchId(param));
            packageReq.SetParameter("nonce_str", GetNoncestr());
            //packageReq.SetParameter("transaction_id", "");
            packageReq.SetParameter("out_trade_no", param.OrderNumber);
            packageReq.SetParameter("out_refund_no", param.RefundNumber);
            packageReq.SetParameter("total_fee", (param.TotalFee.Value).ToString(CultureInfo.InvariantCulture));
            packageReq.SetParameter("refund_fee", param.RefundFee.Value.ToString(CultureInfo.InvariantCulture));
            packageReq.SetParameter("op_user_id", GetConfig.GetMchId(param));
            packageReq.SetParameter("sign", packageReq.CreateMd5Sign());
            var reqXml     = packageReq.ParseXml();
            var httpClient = new HttpUtil();
            httpClient.SetCharset(HttpContext.Current.Request.ContentEncoding.BodyName);
            httpClient.SetCertInfo(GetConfig.GetCertPath(param), GetConfig.GetCertPwd(param));
            var result     = httpClient.Send(reqXml, "https://api.mch.weixin.qq.com/secapi/pay/refund");
            var xe         = XElement.Parse(result, LoadOptions.SetLineInfo);
            var returnCode = xe.GetElement("return_code").Value;
            //退款成功
            if (returnCode.Equals("SUCCESS"))
            {
                var resultCode = xe.GetElement("result_code").Value;
                if (resultCode.Equals("SUCCESS"))
                {
                    var outTradeNo = xe.GetElement("out_trade_no").Value;
                    //在外面回写订单
                    return(new BaseResult()
                    {
                        IsSuccess = true,
                        Data = new Dictionary <string, string>
                        {
                            { "OrderNumber", outTradeNo }
                        }
                    });
                }
            }
            var errCodeDes = xe.GetElement("err_code_des") == null ? "" : xe.GetElement("err_code_des").Value;
            var returnMsg  = xe.GetElement("return_msg") == null ? "" : xe.GetElement("return_msg").Value;

            return(new BaseResult()
            {
                IsSuccess = false, Message = returnMsg + errCodeDes
            });

            #endregion
        }