Beispiel #1
0
        /// <summary>
        /// 短链接转换接口
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string ShortUrl(string data)
        {
            var urlFormat = "https://api.mch.weixin.qq.com/tools/shorturl";

            var          formDataBytes = data == null ? new byte[0] : Encoding.UTF8.GetBytes(data);
            MemoryStream ms            = new MemoryStream();

            ms.Write(formDataBytes, 0, formDataBytes.Length);
            ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置
            return(RequestUtility.HttpPost(urlFormat, null, ms));
        }
Beispiel #2
0
        public static string Unifiedorder(string data, int timeOut = Config.TIME_OUT)
        {
            var urlFormat = "https://api.mch.weixin.qq.com/pay/unifiedorder";

            var          formDataBytes = data == null ? new byte[0] : Encoding.UTF8.GetBytes(data);
            MemoryStream ms            = new MemoryStream();

            ms.Write(formDataBytes, 0, formDataBytes.Length);
            ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置
            return(RequestUtility.HttpPost(urlFormat, null, ms, timeOut: timeOut));
        }
Beispiel #3
0
        public static string MicroPay(string data)
        {
            var urlFormat = ReurnPayApiUrl("https://api.mch.weixin.qq.com/{0}pay/micropay");

            var          formDataBytes = data == null ? new byte[0] : Encoding.UTF8.GetBytes(data);
            MemoryStream ms            = new MemoryStream();

            ms.Write(formDataBytes, 0, formDataBytes.Length);
            ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置
            return(RequestUtility.HttpPost(urlFormat, null, ms));
        }
Beispiel #4
0
        public static string GetTransferInfo(string data, int timeOut = Config.TIME_OUT)
        {
            var urlFormat = ReurnPayApiUrl("https://api.mch.weixin.qq.com/{0}mmpaymkttransfers/gettransferinfo");

            var          formDataBytes = data == null ? new byte[0] : Encoding.UTF8.GetBytes(data);
            MemoryStream ms            = new MemoryStream();

            ms.Write(formDataBytes, 0, formDataBytes.Length);
            ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置
            return(RequestUtility.HttpPost(urlFormat, null, ms, timeOut: timeOut));
        }
Beispiel #5
0
        /// <summary>
        /// 对账单接口
        /// https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_6
        /// </summary>
        /// <param name="dataInfo"></param>
        /// <returns></returns>
        public static string DownloadBill(TenPayV3DownloadBillRequestData dataInfo)
        {
            var          urlFormat     = ReurnPayApiUrl("https://api.mch.weixin.qq.com/{0}pay/downloadbill");
            var          data          = dataInfo.PackageRequestHandler.ParseXML();
            var          formDataBytes = data == null ? new byte[0] : Encoding.UTF8.GetBytes(data);
            MemoryStream ms            = new MemoryStream();

            ms.Write(formDataBytes, 0, formDataBytes.Length);
            ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置
            return(RequestUtility.HttpPost(urlFormat, null, ms, encoding: Encoding.UTF8));
        }
Beispiel #6
0
        public ActionResult OAuthCallback(string code, string state, string returnUrl, int weixinId = 18635)
        {
            if (string.IsNullOrEmpty(code) || string.IsNullOrEmpty(state))
            {
                return(Content("您拒绝了授权,请返回。"));
            }

            if (state != "NCF")
            {
                return(Content("验证失败!请从正规途径进入!"));
            }

            try
            {
                ServicePointManager.ServerCertificateValidationCallback =
                    (s, certificate, chain, sslPolicyErrors) => true;

                var url = "https://weixin.senparc.com/APIs/User_Info";

                var userInfoJson = RequestUtility.HttpPost(url,
                                                           formData: new Dictionary <string, string>
                {
                    { "code", code },
                    { "appId", _senparcWeixinSetting.WeixinAppId },
                    { "appSecret", _senparcWeixinSetting.WeixinAppSecret }
                }
                                                           );
                LogUtility.Account.Debug($"UserInfoJson:{userInfoJson}");
                var userInfo = JsonConvert.DeserializeObject <UserInfoJson>(userInfoJson);

                if (userInfo == null || userInfo.openid == null)
                {
                    //获取出错
                    var errorResult = JsonConvert.DeserializeObject <WxJsonResult>(userInfoJson);
                    return(RenderError($"错误:{errorResult.errcode.ToString()}"));
                }

                var account = _accountService.CreateOrUpdateBySenparcWeixin(userInfo);

                _accountService.Login(account.UserName, true, null, true);

                if (string.IsNullOrWhiteSpace(returnUrl))
                {
                    return(RedirectToAction(nameof(Index), "Home", new { area = "User" }));
                }
                //转到用户一开始访问的页面
                return(Redirect(returnUrl));
            }
            catch (ErrorJsonResultException ex)
            {
                return(Content(ex.Message));
            }
        }
Beispiel #7
0
        public string UploadForeverVideo(string file, string title, string introduction, int timeOut = 40000)
        {
            var url            = GetAccessApiUrl("add_material", ApiName);
            var fileDictionary = new Dictionary <string, string>
            {
                ["media"]       = file,
                ["description"] = string.Format("{{\"title\":\"{0}\", \"introduction\":\"{1}\"}}", title, introduction)
            };
            var result = RequestUtility.HttpPost(url, null, fileDictionary, null, timeOut);

            return(result);
        }
        /// <summary>
        /// <para>查询企业付款银行卡</para>
        /// <para>注意:请求需要双向证书</para>
        /// </summary>
        /// <param name="dataInfo"></param>
        /// <returns></returns>
        public static QueryBankResult QueryBank(TenPayV3QueryBankRequestData dataInfo)
        {
            var urlFormat = ReurnPayApiUrl("https://api.mch.weixin.qq.com/{0}mmpaysptrans/query_bank");

            var data = dataInfo.PackageRequestHandler.ParseXML();//获取XML
            var formDataBytes = data == null ? new byte[0] : Encoding.UTF8.GetBytes(data);
            MemoryStream ms = new MemoryStream();
            ms.Write(formDataBytes, 0, formDataBytes.Length);
            ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置
            var resultXml = RequestUtility.HttpPost(urlFormat, null, ms);
            return new QueryBankResult(resultXml);
        }
Beispiel #9
0
        /// <summary>
        /// 用于商户的企业付款操作进行结果查询,返回付款操作详细结果。
        /// </summary>
        /// <param name="dataInfo"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static GetTransferInfoResult GetTransferInfo(TenPayV3GetTransferInfoRequestData dataInfo, int timeOut = Config.TIME_OUT)
        {
            var          urlFormat     = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo";
            var          data          = dataInfo.PackageRequestHandler.ParseXML();
            var          formDataBytes = data == null ? new byte[0] : Encoding.UTF8.GetBytes(data);
            MemoryStream ms            = new MemoryStream();

            ms.Write(formDataBytes, 0, formDataBytes.Length);
            ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置
            var result = RequestUtility.HttpPost(urlFormat, null, ms, timeOut: timeOut);

            return(new GetTransferInfoResult(result));
        }
Beispiel #10
0
        /// <summary>
        /// <para>获取 RSA 加密公钥接口</para>
        /// <para>https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=24_7&index=4</para>
        /// </summary>
        /// <param name="dataInfo"></param>
        /// <returns></returns>
        public static GetPublicKeyResult GetPublicKey(TenPayV3QueryBankRequestData dataInfo)
        {
            //TODO:官方文档没有明确此接口是否支持沙箱
            var urlFormat = ReurnPayApiUrl("https://fraud.mch.weixin.qq.com/{0}risk/getpublickey");

            var data = dataInfo.PackageRequestHandler.ParseXML();//获取XML
            var formDataBytes = data == null ? new byte[0] : Encoding.UTF8.GetBytes(data);
            MemoryStream ms = new MemoryStream();
            ms.Write(formDataBytes, 0, formDataBytes.Length);
            ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置
            var resultXml = RequestUtility.HttpPost(urlFormat, null, ms);
            return new GetPublicKeyResult(resultXml);
        }
Beispiel #11
0
        /// <summary>
        /// 刷卡支付
        /// 提交被扫支付
        /// </summary>
        /// <param name="dataInfo"></param>
        /// <returns></returns>
        public static MicropayResult MicroPay(TenPayV3MicroPayRequestData dataInfo)
        {
            var          urlFormat     = "https://api.mch.weixin.qq.com/pay/micropay";
            var          data          = dataInfo.PackageRequestHandler.ParseXML();
            var          formDataBytes = data == null ? new byte[0] : Encoding.UTF8.GetBytes(data);
            MemoryStream ms            = new MemoryStream();

            ms.Write(formDataBytes, 0, formDataBytes.Length);
            ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置
            var resultXml = RequestUtility.HttpPost(urlFormat, null, ms);

            return(new MicropayResult(resultXml));
        }
Beispiel #12
0
        /// <summary>
        ///     订单查询接口
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string OrderQuery(string data)
        {
            var urlFormat = "https://api.mch.weixin.qq.com/pay/orderquery";

            var formDataBytes = data == null ? new byte[0] : Encoding.UTF8.GetBytes(data);

            using (var ms = new MemoryStream())
            {
                ms.Write(formDataBytes, 0, formDataBytes.Length);
                ms.Seek(0, SeekOrigin.Begin); //设置指针读取位置
                return(RequestUtility.HttpPost(urlFormat, null, ms));
            }
        }
Beispiel #13
0
        public static PictureResult UploadImg(string accessToken, string fileName)
        {
            var urlFormat = "https://api.weixin.qq.com/merchant/common/upload_img?access_token={0}&filename={1}";
            var url       = string.IsNullOrEmpty(accessToken) ? urlFormat : string.Format(urlFormat, accessToken, fileName);

            var json = new PictureResult();

            using (var fs = FileHelper.GetFileStream(fileName))
            {
                var jsonText = RequestUtility.HttpPost(url, null, fs);
                json = Post.GetResult <PictureResult>(jsonText);
            }
            return(json);
        }
Beispiel #14
0
        public static PictureResult UploadImg(string accessToken, string fileName)
        {
            var urlFormat = Config.ApiMpHost + "/merchant/common/upload_img?access_token={0}&filename={1}";
            var url       = string.IsNullOrEmpty(accessToken) ? urlFormat : string.Format(urlFormat, accessToken.AsUrlData(), fileName.AsUrlData());

            var json = new PictureResult();

            using (var fs = FileHelper.GetFileStream(fileName))
            {
                var jsonText = RequestUtility.HttpPost(CommonDI.CommonSP, url, null, fs);
                json = Senparc.Weixin.HttpUtility.Post.GetResult <PictureResult>(jsonText);
            }
            return(json);
        }
Beispiel #15
0
        /// <summary>
        /// 向微信公众平台API发送信息的公共方法
        /// </summary>
        /// <param name="urlFormat">API接口地址格式</param>
        /// <param name="accessToken">微信公众号访问授权AccessToken</param>
        /// <param name="data">POST提交的数据</param>
        /// <param name="querys">除了AccessToken还需要传递的其他参数</param>
        /// <returns></returns>
        public static T Post <T>(string accessToken, string urlFormat, object data, params string[] querys)
        {
            var url = GetApiUrl(urlFormat, accessToken, querys);
            SerializerHelper serializerHelper = new SerializerHelper();
            var jsonString = serializerHelper.GetJsonString(data);

            using (MemoryStream ms = new MemoryStream())
            {
                var bytes = Encoding.UTF8.GetBytes(jsonString);
                ms.Write(bytes, 0, bytes.Length);
                ms.Seek(0, SeekOrigin.Begin);
                string result = RequestUtility.HttpPost(url, ms, null);
                return(GetResult <T>(result));
            }
        }
Beispiel #16
0
        /// <summary>
        /// 统一支付接口
        /// 统一支付接口,可接受JSAPI/NATIVE/APP 下预支付订单,返回预支付订单号。NATIVE 支付返回二维码code_url。
        /// </summary>
        /// <param name="dataInfo">微信支付需要post的Data数据</param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static UnifiedorderResult Unifiedorder(TenPayV3UnifiedorderRequestData dataInfo, int timeOut = Config.TIME_OUT)
        {
            var urlFormat = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            var data      = dataInfo.PackageRequestHandler.ParseXML();//获取XML
            //throw new Exception(data.HtmlEncode());
            MemoryStream ms            = new MemoryStream();
            var          formDataBytes = data == null ? new byte[0] : Encoding.UTF8.GetBytes(data);

            ms.Write(formDataBytes, 0, formDataBytes.Length);
            ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置

            var resultXml = RequestUtility.HttpPost(urlFormat, null, ms, timeOut: timeOut);

            return(new UnifiedorderResult(resultXml));
        }
Beispiel #17
0
        public ApiResult GetWxUrlToMobile(int money, string userId)
        {
            appid = "wx226d38e96ed8f01e";
            mchid = "1375852802";
            key   = "1de60212dceafe2b4fdb621bd6f04288";

            var no    = GetRandom();
            var total = (money * 100).ToString();

            notifyUrl = ApiHost + "/api/Recharge/WxNotify";
            var result = new ApiResult <string>();

            if (_service.AddComeOutRecord(no, money, 1, int.Parse(userId)))
            {
                RequestHandler packageReqHandler = new RequestHandler(null);
                packageReqHandler.SetParameter("appid", appid);  //APPID
                packageReqHandler.SetParameter("mch_id", mchid); //商户号
                packageReqHandler.SetParameter("nonce_str", TenPayV3Util.GetNoncestr());
                packageReqHandler.SetParameter("body", "金币充值");
                packageReqHandler.SetParameter("out_trade_no", no);               //订单号
                //packageReqHandler.SetParameter("total_fee", total); //金额,以分为单位
                packageReqHandler.SetParameter("total_fee", "1");                 //金额,以分为单位
                packageReqHandler.SetParameter("spbill_create_ip", Tool.GetIP()); //IP
                packageReqHandler.SetParameter("notify_url", notifyUrl);          //回调地址
                packageReqHandler.SetParameter("trade_type", "MWEB");             //这个不可以改。固定为Mweb
                packageReqHandler.SetParameter("sign", packageReqHandler.CreateMd5Sign("key", key));
                string       data          = packageReqHandler.ParseXML();
                var          urlFormat     = "https://api.mch.weixin.qq.com/pay/unifiedorder";
                var          formDataBytes = data == null ? new byte[0] : Encoding.UTF8.GetBytes(data);
                MemoryStream ms            = new MemoryStream();
                ms.Write(formDataBytes, 0, formDataBytes.Length);
                ms.Seek(0, SeekOrigin.Begin);

                var obj = RequestUtility.HttpPost(urlFormat, null, ms);

                var    res      = System.Xml.Linq.XDocument.Parse(obj);
                string mweb_url = res.Element("xml").Element("mweb_url").Value + "&redirect_url=www.izk138.com://pay=1";
                result.Data = mweb_url;

                LogHelper.Info("notifyUrl:" + notifyUrl);

                return(result);
            }
            else
            {
                return(new ApiResult(10000, "生成订单失败"));
            }
        }
Beispiel #18
0
        /// <summary>
        /// 获取Xml结果。
        /// </summary>
        /// <param name="messageHandler"></param>
        /// <param name="url"></param>
        /// <param name="token"></param>
        /// <param name="stream"></param>
        /// <param name="useWeiWeiHiKey">是否使用WeiWeiHiKey,如果使用,则token为WeiWeiHiKey</param>
        /// <param name="timeOut">代理请求超时时间(毫秒)</param>
        /// <returns></returns>
        public static string RequestXml(this IMessageHandler messageHandler, string url, string token, Stream stream, bool useWeiWeiHiKey = false, int timeOut = AGENT_TIME_OUT)
        {
            if (messageHandler != null)
            {
                messageHandler.UsedMessageAgent = true;
            }
            string timestamp = DateTime.Now.Ticks.ToString();
            string nonce     = "GodBlessYou";
            string signature = CheckSignature.GetSignature(timestamp, nonce, token);

            url += string.Format("{0}signature={1}&timestamp={2}&nonce={3}",
                                 url.Contains("?") ? "&" : "?", signature.AsUrlData(), timestamp.AsUrlData(), nonce.AsUrlData());
            var responseXml = RequestUtility.HttpPost(url, null, stream, timeOut: timeOut);

            return(responseXml);
        }
        public ActionResult GetAndUploadImage(string url = "https://sdk.weixin.senparc.com/images/book-cover-front-small-3d-transparent.png")
        {
            var fileName = Server.MapPath("~/App_Data/DownloadImage_{0}.jpg".FormatWith(DateTime.Now.Ticks));

            using (var ms = new MemoryStream())
            {
                Senparc.CO2NET.HttpUtility.Get.Download(url, ms);
                ms.Seek(0, SeekOrigin.Begin);

                //上传流
                var uploadUrl = "http://localhost:60716/Request/UploadImage";
                RequestUtility.HttpPost(uploadUrl, null, ms);
            }

            return(Content("图片已保存到:" + fileName));
        }
Beispiel #20
0
        public void PostTest()
        {
            var    data   = "Jeffrey";
            Stream stream = new MemoryStream();
            var    bytes  = Encoding.UTF8.GetBytes(data);

            stream.Write(bytes, 0, bytes.Length);
            stream.Seek(0, SeekOrigin.Begin);

            var cookieContainer = new CookieContainer();
            var url             = "https://localhost:44335/ForTest/PostTest";//使用.NET 4.5的Sample
            var result          = RequestUtility.HttpPost(BaseTest.serviceProvider, url,
                                                          cookieContainer, stream, useAjax: true);

            Console.WriteLine(result);

            Assert.IsNotNull(result);
        }
Beispiel #21
0
        public void PostJsonDataTest()
        {
            var    data   = @"{""name"":""hardenzhang"",""longitude"":""113.323753357"",""latitude"":""23.0974903107"",""province"":""广东省"",""city"":""广州市"",""district"":""海珠区"",""address"":""TTT"",""category"":""美食: 中餐厅"",""telephone"":""12345678901"",""photo"":""http://mmbiz.qpic.cn/mmbiz_png/tW66AWE2K6ECFPcyAcIZTG8RlcR0sAqBibOm8gao5xOoLfIic9ZJ6MADAktGPxZI7MZLcadZUT36b14NJ2cHRHA/0?wx_fmt=png"",""license"":""http://mmbiz.qpic.cn/mmbiz_png/tW66AWE2K6ECFPcyAcIZTG8RlcR0sAqBibOm8gao5xOoLfIic9ZJ6MADAktGPxZI7MZLcadZUT36b14NJ2cHRHA/0?wx_fmt=png"",""introduct"":""test"",""districtid"":""440105""}";
            Stream stream = new MemoryStream();
            var    bytes  = Encoding.UTF8.GetBytes(data);

            stream.Write(bytes, 0, bytes.Length);
            stream.Seek(0, SeekOrigin.Begin);

            var cookieContainer = new CookieContainer();
            var accesstoken     = "34_WeSuCDgRVtJ0KfPlS0fNdMtBZ4XQDes54MIHt4HlaFkpkItYpLfr0OlfLsntE73eWK_jVifGWxoV2zygK4J2tE6U4eDnNUeLupAkSqf83WMh-6QgNPK9_f6r8xiMlNzVald2l1sKyaQcDPHgSXPlCGAZEW";
            var url             = "https://api.weixin.qq.com/wxa/create_map_poi?access_token=" + accesstoken;
            var result          = RequestUtility.HttpPost(BaseTest.serviceProvider, url,
                                                          cookieContainer, stream, useAjax: false);

            Console.WriteLine(result);

            Assert.IsNotNull(result);
        }
Beispiel #22
0
        /// <summary>
        /// 获取Xml结果。
        /// </summary>
        /// <param name="messageHandler"></param>
        /// <param name="url"></param>
        /// <param name="token"></param>
        /// <param name="stream"></param>
        /// <param name="useNeuCharKey">是否使用WeiWeiHiKey,如果使用,则token为WeiWeiHiKey</param>
        /// <param name="timeOut">代理请求超时时间(毫秒)</param>
        /// <returns></returns>
        public static string RequestXml(this IMessageHandlerBase messageHandler, string url, string token, Stream stream, bool useNeuCharKey = false, int timeOut = AGENT_TIME_OUT)
        {
            if (messageHandler != null)
            {
                messageHandler.UsedMessageAgent = true;
            }
            string timestamp = SystemTime.Now.Ticks.ToString();
            string nonce     = "GodBlessYou";
            string signature = CheckSignatureWeChat.GetSignature(timestamp, nonce, token);

            url += string.Format("{0}signature={1}&timestamp={2}&nonce={3}",
                                 url.Contains("?") ? "&" : "?", signature.AsUrlData(), timestamp.AsUrlData(), nonce.AsUrlData());

            stream.Seek(0, SeekOrigin.Begin);
            var responseXml = RequestUtility.HttpPost(url, null, stream, timeOut: timeOut);

            //WeixinTrace.SendApiLog("RequestXmlUrl:" + url, responseXml);
            return(responseXml);
        }
Beispiel #23
0
        private MediaList_NewsResult GetNewsMediaList(string accessToken, int offset,
                                                      int count, int timeOut = 10000)
        {
            string urlFormat = string.Format("https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token={0}", accessToken.AsUrlData());
            var    data      = new
            {
                type   = "news",
                offset = offset,
                count  = count
            };

            using (MemoryStream memoryStream = new MemoryStream())
            {
                byte[] bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
                memoryStream.Write(bytes, 0, bytes.Length);
                memoryStream.Seek(0L, SeekOrigin.Begin);
                string returnText = RequestUtility.HttpPost(urlFormat, null, memoryStream, null, null, Encoding.UTF8, null, timeOut);
                return(JsonConvert.DeserializeObject <MediaList_NewsResult>(returnText));
            }
        }
        public ActionResult GetImage(string url = "https://sdk.weixin.senparc.com/images/book-cover-front-small-3d-transparent.png")
        {
            var filePath = Server.MapPath("~/App_Data/");
            //Server.MapPath("~/App_Data/DownloadImage_{0}.jpg".FormatWith(DateTime.Now.Ticks));
            var fileName    = Senparc.CO2NET.HttpUtility.Get.Download(url, filePath);
            var newFileName = fileName + ".png";

            System.IO.File.Move(fileName, newFileName);

            //Form 表单上传本地文件
            var dic = new Dictionary <string, string>();

            dic["file"] = newFileName;
            var uploadUrl = "http://localhost:60716/Request/UploadFile";
            //ServicePointManager.Expect100Continue = false;

            var uploadResult = RequestUtility.HttpPost(uploadUrl, fileDictionary: dic);

            return(Content("图片已保存到:" + fileName + "<br/>" + uploadResult));
        }
Beispiel #25
0
        /// <summary>
        /// 上传永久素材(图片(image)、语音(voice)、视频(video)和缩略图(thumb))
        /// </summary>
        /// <param name="file"></param>
        /// <param name="title"></param>
        /// <param name="introduction"></param>
        /// <param name="materialType"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public UploadForeverMaterialApiResult UploadForeverMaterial(string file, string title, string introduction, MaterialType materialType, int timeOut = 40000)
        {
            var url = GetAccessApiUrl("add_material", ApiName, urlParams: new Dictionary <string, string>()
            {
                { "type", materialType.ToString() }
            });
            var resultStr = RequestUtility.HttpPost(
                url,
                null,
                null,
                new Dictionary <string, string>
            {
                ["media"] = file,
            }, encoding: Encoding.UTF8);
            var result = JsonConvert.DeserializeObject <UploadForeverMaterialApiResult>(resultStr);

            if (result != null)
            {
                result.DetailResult = resultStr;
            }
            RefreshAccessTokenWhenTimeOut(result);
            return(result);
        }
        public static JsonMessage Process(HttpRequestModel model)
        {
            JsonMessage slt = new JsonMessage()
            {
                Flag = false
            };

            if (model == null)
            {
                slt.Message = "参数错误";
                return(slt);
            }
            if (string.IsNullOrEmpty(model.Url))
            {
                slt.Message = "请填写网址";
                return(slt);
            }
            if (string.IsNullOrEmpty(model.Method))
            {
                slt.Message = "请不要篡改请求方式";
                return(slt);
            }
            model.Url = model.Url.ToLower();
            if (!model.Url.StartsWith("http://"))
            {
                model.Url = "http://" + model.Url;
            }
            if (!string.IsNullOrEmpty(model.Params))
            {
                if (model.Params.StartsWith("?"))
                {
                    model.Params = model.Params.Replace("?", "");
                }
                if (model.Method == "get")
                {
                    if (model.Url.IndexOf("?") > 0)
                    {
                        model.Url = model.Url + "&" + model.Params;
                    }
                    else
                    {
                        model.Url = model.Url + "?" + model.Params;
                    }
                }
            }
            try {
                switch (model.Method)
                {
                case "get":
                    slt.Flag = true;
                    slt.Data = RequestUtility.HttpGet(model.Url);
                    break;

                case "post":
                    slt.Flag = true;
                    Stream queryStream = RequestUtility.GetQueryStream(model.Params);
                    slt.Data = RequestUtility.HttpPost(model.Url, null, queryStream);
                    break;
                }
            }
            catch (Exception ex) {
                slt.Flag    = false;
                slt.Message = ex.Message;
            }
            return(slt);
        }
Beispiel #27
0
        public string Transfer(List <CrashApply> applys, Payment payment, string notifyUrl)
        {
            int successCount = 0;

            foreach (var crashApply in applys)
            {
                if (crashApply.ApplyState != ApplyState.ApplyPassed)
                {
                    Logger.Operation($"提现转账失败,扣除冻结金额处理失败,TransactionNo:{crashApply.TransactionNo},原因:提现转账申请状态不合法", PaymentProcessModule.Instance, Security.SecurityLevel.Danger);
                    continue;
                }
                //判断是否已经存在
                var oauth = _currencyService.GetSingleByConditon <UserOAuth>(
                    o => o.OAuthType == OAuthType.WeiXin && o.MemberId.Equals(crashApply.MemberId, StringComparison.OrdinalIgnoreCase));
                if (oauth == null)
                {
                    using (TransactionScope scope = new TransactionScope())
                    {
                        //其他操作
                        string error;

                        if (_walletService.Thaw(crashApply.MemberId, WalletType.Cash, crashApply.Money, "提现失败", out error))
                        {
                            crashApply.ApplyState = ApplyState.Failure;
                            _currencyService.Update(crashApply);
                            //提交
                            scope.Complete();
                        }
                        else
                        {
                            Logger.Operation($"提现转账失败,扣除冻结金额处理失败,TransactionNo:{crashApply.TransactionNo},原因:{error}", PaymentProcessModule.Instance, Security.SecurityLevel.Danger);
                        }
                    }
                    continue;
                }

                //创建支付应答对象
                WxRequestHandler packageReqHandler = new WxRequestHandler(HttpContext.Current);
                //初始化
                packageReqHandler.Init();

                var nonceStr = TenPayV3Util.GetNoncestr();
                //设置package订单参数
                packageReqHandler.SetParameter("mch_appid", AppId);                                                //公众账号ID
                packageReqHandler.SetParameter("mchid", MchId);                                                    //商户号
                packageReqHandler.SetParameter("nonce_str", nonceStr);                                             //随机字符串
                packageReqHandler.SetParameter("partner_trade_no", crashApply.TransactionNo);
                packageReqHandler.SetParameter("openid", oauth.OAuthId);
                packageReqHandler.SetParameter("check_name", "OPTION_CHECK");
                packageReqHandler.SetParameter("re_user_name", crashApply.RealName);
                packageReqHandler.SetParameter("amount", (crashApply.Money * 100).ToString());
                packageReqHandler.SetParameter("desc", "余额提现");
                packageReqHandler.SetParameter("spbill_create_ip", RemoteIP);

                string sign = packageReqHandler.CreateMd5Sign("key", Key);
                packageReqHandler.SetParameter("sign", sign);   //签名

                string data = packageReqHandler.ParseXML();
                Logger.Debug(data);
                var urlFormat = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";

                var          formDataBytes = data == null ? new byte[0] : Encoding.UTF8.GetBytes(data);
                MemoryStream ms            = new MemoryStream();
                ms.Write(formDataBytes, 0, formDataBytes.Length);
                ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置
                X509Certificate2 cer = new X509Certificate2($"{AppDomain.CurrentDomain.BaseDirectory}/Config/weixin_apiclient_cert.p12", MchId);

                try
                {
                    var result = RequestUtility.HttpPost(urlFormat, null, ms, timeOut: 10000, cer: cer, checkValidationResult: true);
                    //                    @"<xml>
                    //<return_code><![CDATA[SUCCESS]]></return_code>
                    //<return_msg><![CDATA[]]></return_msg>
                    //<mch_appid><![CDATA[wx8526f7a589c11f7f]]></mch_appid>
                    //<mchid><![CDATA[1393035002]]></mchid>
                    //<device_info><![CDATA[]]></device_info>
                    //<nonce_str><![CDATA[06138BC5AF6023646EDE0E1F7C1EAC75]]></nonce_str>
                    //<result_code><![CDATA[SUCCESS]]></result_code>
                    //<partner_trade_no><![CDATA[2016101312011511532]]></partner_trade_no>
                    //<payment_no><![CDATA[1000018301201610130371564966]]></payment_no>
                    //<payment_time><![CDATA[2016-10-13 19:48:11]]></payment_time>
                    //</xml>"

                    //                    @"<xml>
                    //<return_code><![CDATA[SUCCESS]]></return_code>
                    //<return_msg><![CDATA[付款金额不能小于最低限额.]]></return_msg>
                    //<result_code><![CDATA[FAIL]]></result_code>
                    //<err_code><![CDATA[AMOUNT_LIMIT]]></err_code>
                    //<err_code_des><![CDATA[付款金额不能小于最低限额.]]></err_code_des>
                    //</xml>"
                    var res           = XDocument.Parse(result);
                    var resultCodeXml = res.Element("xml")?.Element("result_code");
                    if (resultCodeXml != null && resultCodeXml.Value.Equals("SUCCESS", StringComparison.OrdinalIgnoreCase))
                    {
                        successCount++;
                        //提交成功
                        crashApply.ApplyState   = ApplyState.Transferred;
                        crashApply.TransferTime = DateTime.Now;
                        crashApply.Description  = "微信提现成功";
                        _currencyService.Update(crashApply);
                        string error;
                        if (
                            !_walletService.Draw(crashApply.MemberId, WalletType.Cash, crashApply.Money, "提现支出",
                                                 out error, null, null, true))
                        {
                            Logger.Operation($"提现转账成功,扣除冻结金额处理失败,TransactionNo:{crashApply.TransactionNo},原因:{error}",
                                             PaymentProcessModule.Instance, Security.SecurityLevel.Danger);
                        }

                        _systemMessageService.CreatePushSystemMessage("提现打款", "您申请的提现已打款,请注意查收", "您申请的提现已打款,请注意查收",
                                                                      crashApply.MemberId, null, null, "CrashApply", WalletModule.Key, MessageCategory.Personal);
                    }
                    else
                    {
                        var returnMsgXml = res.Element("xml")?.Element("return_msg")?.Value;
                        Logger.Operation($"提现转账失败,TransactionNo:{crashApply.TransactionNo},原因:{returnMsgXml}", PaymentProcessModule.Instance, Security.SecurityLevel.Danger);
                    }

                    Logger.Debug(result);
                }
                catch (Exception ex)
                {
                    Logger.Debug(ex, "微信企业付款");
                    Logger.Operation($"提现转账失败,TransactionNo:{crashApply.TransactionNo},未知异常:{ex.Message}", PaymentProcessModule.Instance, Security.SecurityLevel.Danger);

                    continue;
                }
            }

            var resultJson = new DataJsonResult();

            if (successCount < applys.Count)
            {
                resultJson.ErrorMessage = "部分条目处理失败,请查看系统日志";
            }
            resultJson.Success = true; //重置回True
            return(resultJson.ToJson());
        }
Beispiel #28
0
        public void HttpPostTest()
        {
            //return;//已经通过,但需要连接远程测试,太耗时,常规测试时暂时忽略。

            /*
             * 说明:在测试之前请确保url可用
             * 当前默认URL为Sample项目,可以使用Ctrl+F5打开Sample项目,确保可以访问
             */

            //随便找一个存在的测试图片
            var file = "..\\..\\..\\..\\Senparc.Weixin.MP.Sample\\Senparc.Weixin.MP.Sample\\Images\\qrcode.jpg";

            var url = "http://localhost:65395/Media/TestUploadMediaFile/?token={0}&type={1}&contentLength={2}";

            {
                //同步方法测试
                FileStream fs = new FileStream(file, FileMode.Open);

                url = string.Format(url, "TOKEN", UploadMediaFileType.image.ToString(), fs.Length);

                //获取字符串结果
                var actualResult = RequestUtility.HttpPost(url, new CookieContainer(), fs, encoding: null);
                Assert.IsNotNull(actualResult);
                Console.WriteLine(actualResult);

                //比较强类型示例的结果
                UploadTemporaryMediaResult resultEntity = Post.GetResult <UploadTemporaryMediaResult>(actualResult);
                Assert.IsNotNull(resultEntity);
                Assert.AreEqual(UploadMediaFileType.image, resultEntity.type);
                Assert.AreEqual("MEDIA_ID", resultEntity.media_id);
                Assert.AreEqual(123456789, resultEntity.created_at);
            }

            {
                //异步方法测试
                var finished = false;
                Task.Factory.StartNew(async() =>
                {
                    Console.WriteLine("开始异步方法测试");

                    FileStream fs = new FileStream(file, FileMode.Open);

                    url = string.Format(url, "TOKEN", UploadMediaFileType.image.ToString(), fs.Length);

                    //获取字符串结果
                    var actualResult = await RequestUtility.HttpPostAsync(url, new CookieContainer(), fs, encoding: null);
                    Assert.IsNotNull(actualResult);
                    Console.WriteLine(actualResult);

                    //比较强类型示例的结果
                    UploadTemporaryMediaResult resultEntity = Post.GetResult <UploadTemporaryMediaResult>(actualResult);
                    Assert.IsNotNull(resultEntity);
                    Assert.AreEqual(UploadMediaFileType.image, resultEntity.type);
                    Assert.AreEqual("MEDIA_ID", resultEntity.media_id);
                    Assert.AreEqual(123456789, resultEntity.created_at);
                    finished = true;
                });

                while (!finished)
                {
                    Thread.Sleep(10);
                }
            }
        }