Esempio n. 1
0
 /// <summary>
 /// 必须传入Debug,Url,可选传入:WeChatPublic
 /// </summary>
 /// <param name="param"></param>
 /// <returns></returns>
 public static BaseResult CreateWxConfig(WeChatParam param)
 {
     try
     {
         var noncestr    = PayUtil.GetNoncestr();
         var timestamp   = PayUtil.GetTimestamp();
         var jsapiTicket = TokenHelper.GetJsapiTicket();
         if (!jsapiTicket.IsSuccess)
         {
             return(new BaseResult(false, null, jsapiTicket.ErrMsg));
         }
         var appId      = WeChatConfig.GetAppId();
         var packageReq = new RequestHandler();
         packageReq.SetParameter("noncestr", noncestr);
         packageReq.SetParameter("jsapi_ticket", jsapiTicket.Ticket);
         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(new BaseResult(true, result));
     }
     catch (Exception ex)
     {
         return(new BaseResult(false, null, "var error='" + ex.Message.Replace("\r\n", "").Replace("\n", "").Replace("\t", "").Replace("<br>", "").Replace("'", "\"") + "';"));
     }
 }
Esempio n. 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(WeChatConfig.GetKey());
                payReq.SetParameter("appId", WeChatConfig.GetAppId());
                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 + "'}");
            }
        }
Esempio n. 3
0
        /// <summary>
        ///
        /// </summary>
        public static JsapiTicketResult GetJsapiTicket()
        {
            var appId  = WeChatConfig.GetAppId();
            var result = CacheHelper.Get("JsapiTicket" + appId) as JsapiTicketResult;

            if (result == null || string.IsNullOrWhiteSpace(result.Ticket))
            {
                result = HttpHelper.Get <JsapiTicketResult>(ApiList.GetticketUrl, new
                {
                    access_token = GetAccessToken(),
                    type         = "jsapi"
                });

                if (result.ErrMsg != "ok")
                {
                    throw new Exception("获取JsapiTicket失败!" + result.ErrCode + "_" + result.ErrMsg);
                }

                if (result.IsSuccess)
                {
                    CacheHelper.Set("JsapiTicket" + appId, result, result.ExpiresIn - 60);
                }
                else
                {
                    LogHelper.Debug("GetJsapiTicket失败!" + result.ErrMsg, "微信_Fail_");
                }
            }
            return(result);
        }
Esempio n. 4
0
        /// <summary>
        /// 获取access_token。会缓存,过期后自动重新获取新的token。
        /// </summary>
        public static TokenResult GetAccessToken()
        {
            var appId  = WeChatConfig.GetAppId();
            var secret = WeChatConfig.GetSecret();
            var result = CacheHelper.Get("AccessToken" + appId) as TokenResult;

            if (result == null || string.IsNullOrWhiteSpace(result.AccessToken))
            {
                result = HttpHelper.Get <TokenResult>(ApiList.GetTokenUrl, new
                {
                    grant_type = "client_credential",
                    appid      = appId,
                    secret     = secret
                });
                if (result.IsSuccess)
                {
                    CacheHelper.Set("AccessToken" + appId, result, result.ExpiresIn - 60);
                }
                else
                {
                    LogHelper.Debug("GetAccessToken失败!" + result.ErrMsg, "微信_Fail_");
                }
            }
            return(result);
        }
Esempio n. 5
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static ReceiveMsg ParseReceiveMsg()
        {
            var request = HttpContext.Current.Request;
            var sr      = new StreamReader(request.InputStream);

            LogHelper.Debug("开始sr.ReadToEnd()", "微信CallBack_");
            var text = sr.ReadToEnd();

            LogHelper.Debug("text:" + text, "微信CallBack_");
            if (WeChatConfig.IsEncrypt())
            {
                var appId          = WeChatConfig.GetOpenAppId();
                var token          = WeChatConfig.GetOpenToken();
                var encodingAesKey = WeChatConfig.GetOpenDesKey();
                var sMsg           = "";//解密后的内容
                var msg            = new WXBizMsgCrypt(token, encodingAesKey, appId);
                var ret            = msg.DecryptMsg(request.QueryString["msg_signature"], request.QueryString["timestamp"], request.QueryString["nonce"], text, ref sMsg);

                LogHelper.Debug(string.Format("结果代码:{0}\r\n解密前内容:{1}\r\n解密后内容:{2}\r\nmsg_signature:{3}\r\ntimestamp:{4}\r\nnonce:{5}", ret, text, sMsg, request.QueryString["msg_signature"], request.QueryString["timestamp"], request.QueryString["nonce"]), "微信CallBack_");

                text = sMsg;
            }
            var result = Parse(text);

            return(result);
        }
Esempio n. 6
0
        /// <summary>
        /// 将响应写入响应流。
        /// </summary>
        public void Response(bool end = true)
        {
            var response = HttpContext.Current.Response;
            var request  = HttpContext.Current.Request;

            if (response.IsClientConnected)
            {
                var text = ToXml();
                if (WeChatConfig.IsEncrypt())
                {
                    var appId          = WeChatConfig.GetOpenAppId();
                    var token          = WeChatConfig.GetOpenToken();
                    var encodingAesKey = WeChatConfig.GetOpenDesKey();
                    var sMsg           = "";//加密后的内容
                    var msg            = new WXBizMsgCrypt(token, encodingAesKey, appId);
                    var ret            = msg.EncryptMsg(text, request.QueryString["timestamp"], request.QueryString["nonce"], ref sMsg);
                    //var ret = msg.DecryptMsg(request.QueryString["msg_signature"], request.QueryString["timestamp"], request.QueryString["nonce"], text, ref sMsg);

                    LogHelper.Debug(string.Format("结果代码:{0}\r\n加密前内容:{1}\r\n加密后内容:{2}\r\nmsg_signature:{3}\r\ntimestamp:{4}\r\nnonce:{5}", ret, text, sMsg, request.QueryString["msg_signature"], request.QueryString["timestamp"], request.QueryString["nonce"]), "微信CallBack_");

                    text = sMsg;
                }
                response.Write(text);
                if (end)
                {
                    response.Flush();
                    response.Close();
                }
            }
        }
Esempio n. 7
0
        /// <summary>
        /// 传入Code
        /// </summary>
        public static Dictionary <string, string> GetOauth2AccessToken(WeChatParam param)
        {
            var param2 = new
            {
                appid      = WeChatConfig.GetAppId(),
                secret     = WeChatConfig.GetSecret(),
                code       = param.Code,
                grant_type = "authorization_code"
            };
            var dic = HttpHelper.Get <Dictionary <string, string> >(ApiList.GetOauth2AccessTokenUrl, param2);

            return(dic);
        }
Esempio n. 8
0
        /// <summary>
        /// 获取授权公众号的接口调用凭据(令牌)。传入:authorizer_appid(授权方appid)、authorizer_refresh_token(授权方的刷新令牌)、component_verify_ticket(微信后台推送的ticket,此ticket会定时推送)
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static AuthorizerTokenResult GetAuthorizerAccessToken(WeChatParam param)
        {
            if (string.IsNullOrWhiteSpace(param.AuthorizerAppid))
            {
                return(null);
            }
            var token = CacheHelper.Get("AuthorizerAccessToken" + param.AuthorizerAppid) as AuthorizerTokenResult;

            if (token != null && !string.IsNullOrWhiteSpace(token.AuthorizerAccessToken))
            {
                return(token);
            }
            var componentAccessToken = Open.GetComponentToken(new WeChatParam()
            {
                ComponentVerifyTicket = param.ComponentVerifyTicket
            });

            if (!componentAccessToken.IsSuccess)
            {
                return(new AuthorizerTokenResult()
                {
                    IsSuccess = false,
                    ErrMsg = componentAccessToken.ErrMsg
                });
            }
            var result = HttpHelper.Post <AuthorizerTokenResult>(new HttpParam()
            {
                Url       = ApiList.ApiAuthorizerToken,
                PostParam = new
                {
                    component_appid          = WeChatConfig.GetOpenAppId(),
                    authorizer_appid         = param.AuthorizerAppid,
                    authorizer_refresh_token = param.AuthorizerRefreshToken
                },
                GetParam = new
                {
                    component_access_token = componentAccessToken.ComponentAccessToken
                }
            });

            if (result.IsSuccess && !string.IsNullOrWhiteSpace(result.AuthorizerAccessToken))
            {
                CacheHelper.Set("AuthorizerAccessToken" + param.AuthorizerAppid, result,
                                result.ExpiresIn - 60);
            }
            else
            {
                LogHelper.Debug("GetAuthorizerAccessToken失败!" + result.ErrMsg, "微信_Fail_");
            }
            return(result);
        }
Esempio n. 9
0
        /// <summary>
        /// 使用授权码换取公众号的接口调用凭据和授权信息
        /// <para>传入:AuthorizationCode(授权code)、ComponentVerifyTicket(微信后台推送的ticket,此ticket会定时推送)</para>
        /// </summary>
        /// <param name="param"></param>
        public static QueryAuthResult QueryAuth(WeChatParam param)
        {
            var result = CacheHelper.Get("QueryAuth") as QueryAuthResult;

            if (result == null || string.IsNullOrWhiteSpace(result.AuthorizationInfo.AuthorizerAccessToken))
            {
                var token = GetComponentToken(new WeChatParam()
                {
                    ComponentVerifyTicket = param.ComponentVerifyTicket
                });
                if (!token.IsSuccess)
                {
                    return(new QueryAuthResult()
                    {
                        IsSuccess = false,
                        ErrMsg = token.ErrMsg
                    });
                }
                result = HttpHelper.Post <QueryAuthResult>(new HttpParam()
                {
                    Url       = ApiList.ApiQueryAuth,
                    PostParam = new
                    {
                        component_appid    = WeChatConfig.GetOpenAppId(),
                        authorization_code = param.AuthorizationCode
                    },
                    GetParam = new
                    {
                        component_access_token = token.ComponentAccessToken
                    }
                });
                if (result.AuthorizationInfo != null)
                {
                    CacheHelper.Set("QueryAuth", result, result.AuthorizationInfo.ExpiresIn - 60);
                }
                else
                {
                    LogHelper.Debug("QueryAuth失败!" + result.ErrMsg, "微信_Fail_");
                }
            }
            return(result);
        }
Esempio n. 10
0
        /// <summary>
        /// 获取预授权码.该API用于获取预授权码。预授权码用于公众号授权时的第三方平台方安全验证。
        /// <para>传入:ComponentVerifyTicket(微信后台推送的ticket,此ticket会定时推送)</para>
        /// </summary>
        /// <param name="param"></param>
        /// <returns>返回:pre_auth_code(预授权码)、expires_in(有效期,为20分钟)</returns>
        public static CreatePreauthcodeResult GetCreatePreAuthCode(WeChatParam param)
        {
            var result = CacheHelper.Get("PreAuthCode") as CreatePreauthcodeResult;

            if (result == null || string.IsNullOrWhiteSpace(result.PreAuthCode))
            {
                var token = GetComponentToken(new WeChatParam()
                {
                    ComponentVerifyTicket = param.ComponentVerifyTicket
                });
                if (!token.IsSuccess)
                {
                    return(new CreatePreauthcodeResult()
                    {
                        IsSuccess = false,
                        ErrMsg = token.ErrMsg
                    });
                }
                result = HttpHelper.Post <CreatePreauthcodeResult>(new HttpParam()
                {
                    Url       = ApiList.ApiCreatePreauthcode,
                    PostParam = new
                    {
                        component_appid = WeChatConfig.GetOpenAppId()
                    },
                    GetParam = new
                    {
                        component_access_token = token.ComponentAccessToken
                    }
                });
                if (!string.IsNullOrWhiteSpace(result.PreAuthCode))
                {
                    CacheHelper.Set("PreAuthCode", result, result.ExpiresIn);
                }
                else
                {
                    LogHelper.Debug("GetCreatePreAuthCode失败!" + result.ErrMsg, "微信_Fail_");
                }
            }
            return(result);
        }
Esempio n. 11
0
        /// <summary>
        /// 获取第三方平台access_token。该API用于获取第三方平台令牌(component_access_token)
        /// <para>传入:ComponentVerifyTicket(微信后台推送的ticket,此ticket会定时推送)</para>
        /// </summary>
        /// <param name="param"></param>
        /// <returns>返回ComponentAccessToken(第三方平台access_token)</returns>
        public static ComponentTokenResult GetComponentToken(WeChatParam param)
        {
            var result = CacheHelper.Get("ComponentToken") as ComponentTokenResult;

            if (result == null || string.IsNullOrWhiteSpace(result.ComponentAccessToken))
            {
                result = HttpHelper.Post <ComponentTokenResult>(ApiList.ApiComponentToken, new
                {
                    component_appid         = WeChatConfig.GetOpenAppId(),
                    component_appsecret     = WeChatConfig.GetOpenAppSecret(),
                    component_verify_ticket = param.ComponentVerifyTicket
                });
                if (!string.IsNullOrWhiteSpace(result.ComponentAccessToken))
                {
                    CacheHelper.Set("ComponentToken", result, result.ExpiresIn - 60);
                }
                else
                {
                    LogHelper.Debug("GetComponentToken失败!" + result.ErrMsg, "微信_Fail_");
                }
            }
            return(result);
        }
Esempio n. 12
0
        /// <summary>
        /// 验证签名。默认公众号不需要参数。传入authorizer_appid(授权方appid)、authorizer_refresh_token(授权方的刷新令牌)则验证该公众号(用于微信开放平台)、component_verify_ticket(微信后台推送的ticket,此ticket会定时推送)
        /// </summary>
        public bool Check(WeChatParam param = null)
        {
            string token;

            if (param != null && !string.IsNullOrWhiteSpace(param.AuthorizerAppid))
            {
                if (string.IsNullOrWhiteSpace(param.AuthorizerRefreshToken))
                {
                    LogHelper.Debug("参数错误!authorizer_refresh_token必传!", "微信CallBack_");
                    return(false);
                }
                var bs = TokenHelper.GetAuthorizerAccessToken(new WeChatParam()
                {
                    AuthorizerAppid        = param.AuthorizerAppid,
                    AuthorizerRefreshToken = param.AuthorizerRefreshToken,
                    ComponentVerifyTicket  = param.ComponentVerifyTicket
                });
                if (!bs.IsSuccess)
                {
                    return(false);
                }
                token = bs.AuthorizerAccessToken;
            }
            else
            {
                token = WeChatConfig.GetToken();
            }
            var vs = new[] { timestamp, nonce, token }.OrderBy(s => s);
            var str  = string.Join("", vs);
            var copu = FormsAuthentication.HashPasswordForStoringInConfigFile(str, "SHA1");

            if (copu == null)
            {
                return(false);
            }
            return(copu.Equals(signature, StringComparison.CurrentCultureIgnoreCase));
        }
Esempio n. 13
0
        /// <summary>
        /// 传入ProductName,OrderNumber,TotalFee,TimeExpire,OpenId(可选),TradeType,NotifyUrl(可选)
        /// </summary>
        /// <param name="param"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetUnifiedOrder(PayParam param = 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();

            req.SetKey(WeChatConfig.GetKey());
            req.SetParameter("appid", WeChatConfig.GetAppId());
            req.SetParameter("mch_id", WeChatConfig.GetMchId());
            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) ? WeChatConfig.GetNotify() : 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();
            var result = HttpHelper.Post(new HttpParam()
            {
                Url       = ApiList.UnifiedOrderUrl,
                PostParam = reqXml,
                Encoding  = HttpContext.Current.Request.ContentEncoding
            });

            return(result);
        }
Esempio n. 14
0
        /// <summary>
        /// 获取授权方的公众号帐号基本信息。该API用于获取授权方的公众号基本信息,包括头像、昵称、帐号类型、认证类型、微信号、原始ID和二维码图片URL。
        /// <para>传入:AuthorizerAppid(授权方appid)、ComponentVerifyTicket(微信后台推送的ticket,此ticket会定时推送)</para>
        /// </summary>
        /// <param name="param"></param>
        public static GetAuthorizerInfoResult GetAuthorizerInfo(WeChatParam param)
        {
            var token = GetComponentToken(new WeChatParam()
            {
                ComponentVerifyTicket = param.ComponentVerifyTicket
            });

            if (!token.IsSuccess)
            {
                return(new GetAuthorizerInfoResult()
                {
                    IsSuccess = false,
                    ErrMsg = token.ErrMsg
                });
            }
            var str = HttpHelper.Post(new HttpParam()
            {
                Url       = ApiList.ApiGetAuthorizerInfo,
                PostParam =
                    new
                {
                    component_appid  = WeChatConfig.GetOpenAppId(),
                    authorizer_appid = param.AuthorizerAppid
                },
                GetParam = new
                {
                    component_access_token = token.ComponentAccessToken
                }
            });
            var result = JSON.ToObject <GetAuthorizerInfoResult>(str);

            if (!result.IsSuccess)
            {
                LogHelper.Debug("GetAuthorizerInfo失败!" + result.ErrMsg, "微信_Fail_");
            }
            return(result);
        }
Esempio n. 15
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(WeChatConfig.GetKey());
            packageReq.SetParameter("appid", WeChatConfig.GetAppId());
            packageReq.SetParameter("mch_id", WeChatConfig.GetMchId());
            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", WeChatConfig.GetMchId());
            packageReq.SetParameter("sign", packageReq.CreateMd5Sign());
            var reqXml = packageReq.ParseXml();
            var result = HttpHelper.Post(new HttpParam()
            {
                Url       = "https://api.mch.weixin.qq.com/secapi/pay/refund",
                PostParam = reqXml,
                Encoding  = HttpContext.Current.Request.ContentEncoding,
                CertPath  = WeChatConfig.GetCertPath(),
                CertPwd   = WeChatConfig.GetCertPwd()
            });
            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
        }
Esempio n. 16
0
        public static BaseResult Notify()
        {
            try
            {
                var res = new ResponseHandler();
                res.SetKey(WeChatConfig.GetKey());
                var error = "";
                //判断签名
                if (res.IsWXsign(out error))
                {
                    #region 参数
                    var returnCode = res.GetParameter("return_code");
                    //返回信息,如非空,为错误原因签名失败参数格式校验错误
                    var returnMsg = res.GetParameter("return_msg");
                    var appid     = res.GetParameter("appid");

                    //以下字段在 return_code 为 SUCCESS 的时候有返回--------------------------------
                    var mchId      = res.GetParameter("mch_id");
                    var deviceInfo = res.GetParameter("device_info");
                    var nonceStr   = res.GetParameter("nonce_str");
                    var resultCode = res.GetParameter("result_code");
                    var errCode    = res.GetParameter("err_code");
                    var errCodeDes = res.GetParameter("err_code_des");

                    //以下字段在 return_code 和 result_code 都为 SUCCESS 的时候有返回---------------
                    var openid = res.GetParameter("openid");
                    //Y-关注,N-未关注,仅在公众账号类型支付有效
                    var isSubscribe = res.GetParameter("is_subscribe");
                    var tradeType   = res.GetParameter("trade_type");
                    //银行类型,采用字符串类型的银行标识
                    var bankType = res.GetParameter("bank_type");
                    var totalFee = res.GetParameter("total_fee");
                    //货币类型,符合 ISO 4217 标准的三位字母代码,默认人民币:CNY
                    var feeType = res.GetParameter("fee_type");
                    //微信支付订单号
                    var transactionId = res.GetParameter("transaction_id");
                    //商户系统的订单号,与请求一致。
                    var outTradeNo = res.GetParameter("out_trade_no");
                    var attach     = res.GetParameter("attach");
                    //格 式 为yyyyMMddhhmmss
                    var timeEnd = res.GetParameter("time_end");
                    #endregion
                    //支付成功
                    if (!outTradeNo.Equals("") && returnCode.Equals("SUCCESS") && resultCode.Equals("SUCCESS"))
                    {
                        //LogHelper.WriteLog("支付回调:", sbResult.ToString() + "notify > success \r\n",EnumService.LogType.Debug);
                        //在外面回写订单
                        return(new BaseResult()
                        {
                            IsSuccess = true,
                            Data = new Dictionary <string, string>
                            {
                                { "OrderNumber", outTradeNo },
                                { "WeChat", openid },
                            }
                        });
                    }
                    else
                    {
                        //LogHelper.WriteLog("支付回调:", sbResult.ToString() + "notify > total_fee= " + totalFee + " \r\n  err_code_des= " + errCodeDes + " \r\n  result_code= " + resultCode + " \r\n", EnumService.LogType.Exception);
                    }
                }
                else
                {
                    //LogHelper.WriteLog("支付回调:",sbResult.ToString() + "notify > isWXsign= false \r\n" + error, EnumService.LogType.Exception);
                }
            }
            catch (Exception ex)
            {
                //LogHelper.WriteLog("支付回调:",sbResult.ToString() + "notify > ex=" + ex.Message + @ex.StackTrace + @ex.InnerException + " \r\n",  EnumService.LogType.Exception);
            }
            return(new BaseResult()
            {
                IsSuccess = false
            });
        }
Esempio n. 17
0
        /// <summary>
        /// billDate格式 20141212
        /// </summary>
        /// <param name="billDate"></param>
        /// <returns></returns>
        public static BaseResult DownloadBill(string billDate)
        {
            var packageReq = new RequestHandler();

            packageReq.SetKey(WeChatConfig.GetKey());
            packageReq.SetParameter("appid", WeChatConfig.GetAppId());
            packageReq.SetParameter("mch_id", WeChatConfig.GetMchId());
            packageReq.SetParameter("nonce_str", GetNoncestr());
            packageReq.SetParameter("bill_date", billDate);
            packageReq.SetParameter("bill_type", "ALL");
            packageReq.SetParameter("sign", packageReq.CreateMd5Sign());
            var reqXml = packageReq.ParseXml();
            //httpClient.SetCharset(HttpContext.Current.Request.ContentEncoding.BodyName);
            var result = HttpHelper.Post(new HttpParam()
            {
                Url       = ApiList.DownloadBillUrl,
                PostParam = reqXml,
                Encoding  = HttpContext.Current.Request.ContentEncoding
            });

            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
                });
            }
        }