/// <summary> /// 发送语音消息 /// </summary> /// <param name="accessToken"></param> /// <param name="openId"></param> /// <param name="mediaId"></param> /// <returns></returns> public static bool SendVoice(string companyId, string accessToken, string openId, string mediaId) { var data = new { touser = openId, msgtype = "voice", voice = new { media_id = mediaId } }; ResError result = WxHttp.Post(WxUrl.SendMsg.ToFormat(accessToken), data); if (result.errcode == ResCode.请求成功) { return(true); } if (result.errcode == ResCode.获取accessToken时AppSecret错误或者accessToken无效) { WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(companyId); var newAccessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret, true); ResError newResult = WxHttp.Post(WxUrl.SendMsg.ToFormat(newAccessToken), data); if (newResult.errcode == ResCode.请求成功) { return(true); } } TxtLogServices.WriteTxtLogEx("WeiXinBase", "发送语音消息错误!错误代码:{0},说明:{1}", (int)result.errcode, result.errmsg); return(false); }
public ActionResult Index(string companyId) { try { if (string.IsNullOrWhiteSpace(companyId)) { return(RedirectToAction("Index", "BrowseError", new { errorMsg = "请打开扫一扫" })); } WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(companyId); var timeStamp = DateTimeHelper.TransferUnixDateTime(DateTime.Now).ToString(); var nonceStr = StringHelper.GetRndString(16); var url = Request.Url.ToString(); var accessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret, false); var ticket = WxAdvApi.GetTicket(accessToken); string signature = WxService.GetJsApiSignature(nonceStr, ticket.ticket, timeStamp, url); ViewBag.Signature = signature; ViewBag.AppId = config.AppId; ViewBag.Timestamp = timeStamp; ViewBag.NonceStr = nonceStr; return(View()); } catch (Exception ex) { ExceptionsServices.AddExceptionToDbAndTxt("WeiXinPageError", "调用扫码方法异常", ex, LogFrom.WeiXin); return(RedirectToAction("Index", "BrowseError", new { errorMsg = "调用扫码方法异常" })); } }
public static bool SendTemplateMessage <T>(string companyId, string accessToken, string openId, string templateId, string topcolor, T data) { var pdata = new Templete { template_id = templateId, topcolor = topcolor, touser = openId, data = data }; ResError result = WxHttp.Post(WxUrl.TemplateSend.ToFormat(accessToken), pdata); if (result.errcode == ResCode.请求成功) { return(true); } if (result.errcode == ResCode.获取accessToken时AppSecret错误或者accessToken无效) { WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(companyId); var newAccessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret, true); ResError newResult = WxHttp.Post(WxUrl.TemplateSend.ToFormat(newAccessToken), pdata); if (newResult.errcode == ResCode.请求成功) { return(true); } } TxtLogServices.WriteTxtLogEx("WeiXinBase", "发送模板消息错误!错误代码:{0},说明:{1}", (int)result.errcode, result.errmsg); return(false); }
/// <summary> /// 移动用户分组 /// </summary> /// <param name="accessToken"></param> /// <param name="openId"></param> /// <param name="toGroupId"></param> /// <returns></returns> public static bool UpdateUserGroup(string companyId, string accessToken, string openId, int toGroupId) { var data = new { openid = openId, to_groupid = toGroupId }; ResError result = WxHttp.Post(WxUrl.UpdateUserGroup.ToFormat(accessToken), data); if (result.errcode == ResCode.请求成功) { return(true); } if (result.errcode == ResCode.获取accessToken时AppSecret错误或者accessToken无效) { WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(companyId); var newAccessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret, true); ResError newResult = WxHttp.Post(WxUrl.UpdateUserGroup.ToFormat(newAccessToken), data); if (newResult.errcode == ResCode.请求成功) { return(true); } } TxtLogServices.WriteTxtLogEx("WeiXinBase", "移动用户分组发生错误!错误代码:{0},说明:{1}", (int)result.errcode, result.errmsg); return(false); }
public JsonResult PublishMenu(string companyId) { try { WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(companyId); if (config == null || string.IsNullOrWhiteSpace(config.AppId) || string.IsNullOrWhiteSpace(config.AppSecret) || string.IsNullOrWhiteSpace(config.SystemName)) { throw new MyException("获取微信基础信息失败,请确认微信基础信息已配置"); } var accessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret, false); var buttonGroup = ToButtonGroup(WXMenuServices.GetMenus(companyId)); TxtLogServices.WriteTxtLogEx("PublishMenu", JsonHelper.GetJsonString(buttonGroup)); var result = WxApi.CreateMenu(companyId, accessToken, buttonGroup); if (!result) { throw new MyException("发布菜单失败"); } return(Json(MyResult.Success())); } catch (MyException ex) { return(Json(MyResult.Error(ex.Message))); } catch (Exception ex) { ExceptionsServices.AddExceptions(ex, "发布菜单失败"); return(Json(MyResult.Error("发布菜单失败"))); } }
/// <summary> /// 发送音乐消息 /// </summary> /// <param name="accessToken"></param> /// <param name="openId"></param> /// <param name="title">音乐标题(非必须)</param> /// <param name="description">音乐描述(非必须)</param> /// <param name="musicUrl">音乐链接</param> /// <param name="hqMusicUrl">高品质音乐链接,wifi环境优先使用该链接播放音乐</param> /// <param name="thumbMediaId">视频缩略图的媒体ID</param> /// <returns></returns> public static bool SendMusic(string companyId, string accessToken, string openId, string title, string description, string musicUrl, string hqMusicUrl, string thumbMediaId) { var data = new { touser = openId, msgtype = "music", music = new { title = title, description = description, musicurl = musicUrl, hqmusicurl = hqMusicUrl, thumb_media_id = thumbMediaId } }; ResError result = WxHttp.Post(WxUrl.SendMsg.ToFormat(accessToken), data); if (result.errcode == ResCode.请求成功) { return(true); } if (result.errcode == ResCode.获取accessToken时AppSecret错误或者accessToken无效) { WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(companyId); var newAccessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret, true); ResError newResult = WxHttp.Post(WxUrl.SendMsg.ToFormat(newAccessToken), data); if (newResult.errcode == ResCode.请求成功) { return(true); } } TxtLogServices.WriteTxtLogEx("WeiXinBase", "发送音乐消息错误!错误代码:{0},说明:{1}", (int)result.errcode, result.errmsg); return(false); }
/// <summary> /// 删除群发 /// 请注意,只有已经发送成功的消息才能删除删除消息只是将消息的图文详情页失效,已经收到的用户,还是能在其本地看到消息卡片。 /// </summary> /// <param name="accessToken"></param> /// <param name="msgId">发送出去的消息ID</param> /// <returns></returns> public static bool SendAllDelete(string companyId, string accessToken, long msgId) { var data = new { msgid = msgId }; ResError result = WxHttp.Post(WxUrl.SendAllDelete.ToFormat(accessToken), data); if (result.errcode == ResCode.请求成功) { return(true); } if (result.errcode == ResCode.获取accessToken时AppSecret错误或者accessToken无效) { WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(companyId); var newAccessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret, true); ResError newResult = WxHttp.Post(WxUrl.SendAllDelete.ToFormat(newAccessToken), data); if (newResult.errcode == ResCode.请求成功) { return(true); } } TxtLogServices.WriteTxtLogEx("WeiXinBase", "删除群发发生错误!错误代码:{0},说明:{1}", (int)result.errcode, result.errmsg); return(false); }
public ActionResult Index(string preferentialMoney = "0", string payMoney = "0", bool showPreferentialMoney = true, string alreadyPayment = "0", bool showWaitPayMoney = true) { ViewBag.PreferentialMoney = preferentialMoney; ViewBag.PayMoney = payMoney; ViewBag.ShowWaitPayMoney = showWaitPayMoney; ViewBag.ShowPreferentialMoney = showPreferentialMoney; ViewBag.AlreadyPayment = alreadyPayment; bool SupportWeiXinPayment = false; bool SupportAliPayment = false; if (!string.IsNullOrWhiteSpace(GetRequestCompanyId)) { AliPayApiConfig config = AliPayApiConfigServices.QueryAliPayConfig(GetRequestCompanyId); if (config != null) { SupportAliPayment = true; } WX_ApiConfig wxConfig = WXApiConfigServices.QueryWXApiConfig(GetRequestCompanyId); if (wxConfig != null) { SupportWeiXinPayment = true; } } ViewBag.SupportWeiXinPayment = SupportWeiXinPayment; ViewBag.SupportAliPayment = SupportAliPayment; return(PartialView()); }
/// <summary> /// 微信单独授权 type 0-支付 1-岗亭扫码进入 /// </summary> /// <param name="id">ControllerName_actionName_ispayauthorize=0^orderId=123</param> /// <param name="code"></param> /// <param name="state"></param> /// <returns></returns> public ActionResult Index(string id, string code, string state) { try { if (SourceClient != RequestSourceClient.WeiXin) { return(RedirectToAction("Index", "ErrorPrompt", new { message = "请在微信中打开" })); } ClearQRCodeCookie(); WX_ApiConfig config = null; Dictionary <string, string> dicParams = GetRequestParams(id); if (string.IsNullOrWhiteSpace(dicParams["COMPANYID"])) { throw new MyException("获取单位信息失败"); } config = WXApiConfigServices.QueryWXApiConfig(dicParams["COMPANYID"]); if (config == null) { return(RedirectToAction("Index", "ErrorPrompt", new { message = "获取微信配置失败" })); } if (!config.Status) { return(RedirectToAction("Index", "ErrorPrompt", new { message = "该公众号暂停使用,稍后再试!" })); } Session["CurrLoginWeiXinApiConfig"] = config; if (string.IsNullOrEmpty(state)) { string redirectUri = config.Domain.IndexOf("http://", StringComparison.Ordinal) < 0 ? string.Format("http://{0}", config.Domain) : config.Domain; redirectUri = string.Format("{0}/WeiXinAuthorize/{1}", redirectUri, id); TxtLogServices.WriteTxtLogEx("WeiXinAuthorize", "获取微信OpenId请求redirectUri:{0}", redirectUri); string url = WxAdvApi.GetAuthorizeUrl(config.AppId, redirectUri, "1", OAuthScope.snsapi_base); TxtLogServices.WriteTxtLogEx("WeiXinAuthorize", "获取微信OpenId请求url:{0}", url); return(Redirect(url)); } TxtLogServices.WriteTxtLogEx("WeiXinAuthorize", "state不为空进入,id:{0}, code:{1}, state:{2}", id, code, state); if (string.IsNullOrEmpty(code)) { return(RedirectToAction("Index", "ErrorPrompt", new { message = "微信获取授权失败,请重新进入或请联系管理员" })); } var accessToken = WxAdvApi.GetAccessToken(config.AppId, config.AppSecret, code); TxtLogServices.WriteTxtLogEx("WeiXinAuthorize", "调用微信的AccessToken接口:openid:{0}, access_token:{1}", accessToken.openid, accessToken.access_token); if (accessToken == null || string.IsNullOrWhiteSpace(accessToken.openid)) { throw new MyException("获取微信用户信息失败"); } //添加登陆 Response.Cookies.Add(new HttpCookie("SmartSystem_WeiXinOpenId", accessToken.openid)); TxtLogServices.WriteTxtLogEx("WeiXinAuthorize", "获取OpenId成功:openid:{0},cookie openid:{1}", accessToken.openid, WeiXinOpenId); return(Redir(id, accessToken.openid)); } catch (Exception ex) { ExceptionsServices.AddExceptionToDbAndTxt("WeiXinAuthorize", "WeiXinAuthorize方法处理异常", ex, LogFrom.WeiXin); return(RedirectToAction("Index", "ErrorPrompt", new { message = "微信获取授权失败,请重新进入或请联系管理员" })); } }
//public string SendParkingOutNotify(string cmd, string plateNo, string cpid, // string pkname, string indate, string outdate, string durtime, string amount, string app) //{ // return SendParkingOutNotify(cmd,plateNo,cpid,pkname,indate,outdate,durtime,"",amount,app); //} //[HttpPost] public string SendParkingOutNotify(string cmd, string plateNo, string cpid, string pkname, string indate, string outdate, string durtime, string payType, string amount, string app) { if (cmd.IsEmpty()) { return("-4"); } WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(cpid); if (config == null) { return("-1"); } if (!config.Status) { return("-2"); } WX_Info user = WXUserServices.GetWXInfoByPlateNo(plateNo); if (user == null) { return("-3"); } if (cmd == "In") { } else if (cmd == "Out") { bool isApp = app == "1" ? true : false; if (amount.EndsWith("元")) { amount = amount + "元"; } if (payType.IsEmpty()) { //默认 payType = "APP支付"; } bool isSuc = TemplateMessageServices.SendParkOut(config.CompanyID, plateNo, pkname, indate, outdate, durtime, payType, amount, user.OpenID, isApp); if (isSuc) { return("1"); } else { return("0"); } } return(""); }
public WeiXinConversation(string token, Stream inputStream) : base(inputStream) { config = WXApiConfigServices.QueryByToKen(token); if (config == null || string.IsNullOrWhiteSpace(config.AppId) || string.IsNullOrWhiteSpace(config.AppSecret) || string.IsNullOrWhiteSpace(config.Domain) || string.IsNullOrWhiteSpace(config.Token)) { CancelExcute = true; } }
private static WX_ApiConfig GetWX_ApiConfig(string companyId) { WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(companyId); if (config == null || string.IsNullOrWhiteSpace(config.AppId) || string.IsNullOrWhiteSpace(config.AppSecret)) { throw new MyException("获取微信基本配置信息失败"); } return(config); }
public ActionResult AdvanceParkingPayment(decimal orderId) { try { AdvanceParking order = AdvanceParkingServices.QueryByOrderId(orderId); if (order == null) { throw new MyException("支付信息不存在"); } if (order.OrderState != 0) { throw new MyException("支付状态不正确"); } UnifiedPayModel model = UnifiedPayModel.CreateUnifiedModel(order.CompanyID); if (string.IsNullOrWhiteSpace(order.PrepayId)) { string payNotifyAddress = string.Format("{0}{1}", WXApiConfigServices.QueryWXApiConfig(order.CompanyID).Domain, "/WeiXinPayNotify/AdvanceParking"); //预支付 UnifiedPrePayMessage result = PaymentServices.UnifiedPrePay(model.CreatePrePayPackage(order.OrderId.ToString(), ((int)(order.Amount * 100)).ToString(), WeiXinOpenId, "预停车支付", payNotifyAddress)); if (result == null || !result.ReturnSuccess || !result.ResultSuccess || string.IsNullOrEmpty(result.Prepay_Id)) { throw new Exception(string.Format("获取PrepayId 失败,Message:{0}", result.ToXmlString())); } AdvanceParkingServices.UpdatePrepayIdById(result.Prepay_Id, order.OrderId); order.PrepayId = result.Prepay_Id; } WeiXinPaySignModel payModel = new WeiXinPaySignModel() { AppId = model.AppId, Package = string.Format("prepay_id={0}", order.PrepayId), Timestamp = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString(), Noncestr = Util.CreateNoncestr(), }; Dictionary <string, string> nativeObj = new Dictionary <string, string>(); nativeObj.Add("appId", payModel.AppId); nativeObj.Add("package", payModel.Package); nativeObj.Add("timeStamp", payModel.Timestamp); nativeObj.Add("nonceStr", payModel.Noncestr); nativeObj.Add("signType", payModel.SignType); payModel.PaySign = model.GetCftPackage(nativeObj); //生成JSAPI 支付签名 ViewBag.PayModel = payModel; return(View(order)); } catch (MyException ex) { return(PageAlert("Index", "AdvanceParking", new { RemindUserContent = ex.Message })); } catch (Exception ex) { ExceptionsServices.AddExceptionToDbAndTxt("WeiXinPayment_Error", string.Format("预停车支付失败 orderId:{0};openId:{1}", orderId, WeiXinOpenId), ex, LogFrom.WeiXin); return(PageAlert("Index", "AdvanceParking", new { RemindUserContent = "支付异常,请重新支付" })); } }
public static UnifiedPayModel CreateUnifiedModel(string companyId) { UnifiedPayModel wxPayModel = new UnifiedPayModel(); WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(companyId); wxPayModel.SetAppId(config.AppId); wxPayModel.SetKey(config.PartnerKey); wxPayModel.SetPartnerId(config.PartnerId); wxPayModel.SetServerIP(config.ServerIP); return(wxPayModel); }
public static string GenerateQRCode(string companyId, string content, int size, string qrCodeName, string folderName = "QRCode") { QRCodeEncoder.ENCODE_MODE QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; QRCodeEncoder.ERROR_CORRECTION QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M; int border = GetQRCodeBorder(size); string imageUrl = string.Empty; int QRCodeVersion = 0; int QRCodeScale = 5; WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(companyId); if (config != null && !string.IsNullOrWhiteSpace(config.SystemLogo)) { imageUrl = config.SystemLogo; } TxtLogServices.WriteTxtLogEx("GenerateQRCode", imageUrl); var bitmap = GenerateQRCode(content, QRCodeEncodeMode, QRCodeErrorCorrect, QRCodeVersion, QRCodeScale, size, border); if (bitmap == null) { return(string.Empty); } string filePath = string.Format("/Uploads/{2}/{0}.{1}", qrCodeName, "jpg", folderName); TxtLogServices.WriteTxtLogEx("GenerateQRCode", "filePath:" + filePath); string savePath = GetFileSavePath(string.Format("/Uploads/{0}", folderName), string.Format("{0}.{1}", qrCodeName, "jpg")); TxtLogServices.WriteTxtLogEx("GenerateQRCode", "savePath:" + filePath); string pathImage = string.Empty; if (!string.IsNullOrWhiteSpace(imageUrl)) { pathImage = System.Web.HttpContext.Current.Server.MapPath("~" + imageUrl); } if (!string.IsNullOrWhiteSpace(pathImage) && File.Exists(pathImage)) { var logoSize = GetLogoImageSize(size); Image bitmap1 = CombinImage(bitmap, pathImage, logoSize); if (File.Exists(savePath)) { File.Delete(savePath); } bitmap1.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg); bitmap1.Dispose(); } else { if (File.Exists(savePath)) { File.Delete(savePath); } bitmap.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg); bitmap.Dispose(); } return(filePath); }
private WX_ApiConfig GetApiConfig(string id) { TxtLogServices.WriteTxtLogEx("RedirectHandle", "获取微信配置信息,id:{0}", id); var separator = new[] { '|', '_' }; var param = new[] { '^' };//^参数分隔符 var ids = id.Split(separator, StringSplitOptions.RemoveEmptyEntries); var parameters = ids[2].Split(param, StringSplitOptions.RemoveEmptyEntries); if (parameters.Length == 0) { throw new MyException("获取单位失败"); } foreach (var item in parameters) { var parame = item.Split(new[] { '=' }); if (parame.Length == 2) { if (parame[0].ToUpper() == "CID") { WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(parame[1]); if (config == null) { throw new MyException("获取微信配置失败"); } if (config.CompanyID != parame[1]) { throw new MyException("该公众号暂停使用"); } return(config); } if (parame[0] == "PARKINGID" || parame[0] == "PID") { BaseCompany company = CompanyServices.QueryByParkingId(parame[1]); if (company == null) { throw new MyException("获取单位信息失败"); } WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(company.CPID); if (config == null) { throw new MyException("获取微信配置失败"); } if (config.CompanyID != parame[1]) { throw new MyException("该公众号暂停使用"); } return(config); } } } throw new MyException("获取微信配置失败,id:" + id); }
public JsonResult GetWeiXinApiConfig(string companyId) { try { WX_ApiConfig config = WXApiConfigServices.QueryByCompanyId(companyId); return(Json(MyResult.Success(string.Empty, config))); } catch (Exception ex) { ExceptionsServices.AddExceptions(ex, "获取微信API配置信息失败"); return(Json(MyResult.Error("获取配置信息失败"))); } }
public static bool DeleteMenu(string companyId, string accessToken) { ResError result = WxHttp.Get(WxUrl.DeleteMenu.ToFormat(accessToken)); if (result.errcode == ResCode.请求成功) { return(true); } if (result.errcode == ResCode.获取accessToken时AppSecret错误或者accessToken无效) { WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(companyId); var newAccessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret, true); ResError newResult = WxHttp.Get(WxUrl.DeleteMenu.ToFormat(newAccessToken)); return(newResult.errcode == ResCode.请求成功); } return(false); }
//[HttpPost] public string SendParkingInNotify(string cmd, string plateNo, string cpid, string pkname, string indate) { if (cmd.IsEmpty()) { return("-4"); } WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(cpid); if (config == null) { return("-1"); } if (!config.Status) { return("-2"); } WX_Info user = WXUserServices.GetWXInfoByPlateNo(plateNo); if (user == null) { return("-3"); } if (cmd == "In") { bool isSuc = TemplateMessageServices.SendParkIn(config.CompanyID, plateNo, pkname, indate, user.OpenID); if (isSuc) { return("1"); } else { return("0"); } } else if (cmd == "Out") { } return(""); }
private UnifiedPayModel GetUnifiedPayModel(OnlineOrder order, string description, string attach = "") { UnifiedPayModel model = UnifiedPayModel.CreateUnifiedModel(order.CompanyID); if (string.IsNullOrWhiteSpace(order.PrepayId)) { string payNotifyAddress = string.Format("{0}{1}", WXApiConfigServices.QueryWXApiConfig(order.CompanyID).Domain, "/WeiXinPayNotify/Index"); //预支付 string postData = model.CreatePrePayPackage(order.OrderID.ToString(), ((int)(order.Amount * 100)).ToString(), WeiXinOpenId, description, payNotifyAddress, attach); UnifiedPrePayMessage result = PaymentServices.UnifiedPrePay(postData); if (result == null || !result.ReturnSuccess || !result.ResultSuccess || string.IsNullOrEmpty(result.Prepay_Id)) { ExceptionsServices.AddExceptionToDbAndTxt("WeiXinPayment_Error", "预支付", string.Format("postData:{0}", postData), LogFrom.WeiXin); throw new Exception(string.Format("获取PrepayId 失败,Message:{0}", result.ToXmlString())); } OnlineOrderServices.UpdatePrepayIdById(result.Prepay_Id, order.OrderID); order.PrepayId = result.Prepay_Id; } return(model); }
public ActionResult DerateSuccess(string msg, string parkingId, string licensePlate) { try { TxtLogServices.WriteTxtLogEx("QRCodeDerate", string.Format("领取成功,parkingId:{0},licensePlate:{1}", parkingId, licensePlate)); ViewBag.Msg = msg; string hrefUrl = string.Empty; BaseParkinfo parking = ParkingServices.QueryParkingByParkingID(parkingId); if (parking == null) { throw new MyException("获取车场信息失败"); } if (parking.MobilePay == YesOrNo.Yes) { string companyId = CompanyServices.GetCompanyId(parkingId, string.Empty); if (string.IsNullOrWhiteSpace(companyId)) { throw new MyException("获取单位编号失败"); } WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(companyId); if (config == null) { throw new MyException("获取微信配置失败"); } hrefUrl = string.Format("{0}/qrl/qrp_ix_pid={1}^pn={2}", SystemDefaultConfig.SystemDomain, parkingId, licensePlate); } ViewBag.HrefUrl = hrefUrl; ViewBag.LicensePlate = licensePlate; ViewBag.DerateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); return(View()); } catch (Exception ex) { TxtLogServices.WriteTxtLogEx("QRCodeDerate", "提示优免结果出错", ex); return(RedirectToAction("BrowseError", "QRCodeDerate", new { errorMsg = "领取优免券成功,但是处理其他业务异常了【不影响优免券的正常使用】" })); } }
public JsonResult AddOrUpdate(WX_ApiConfig config) { try { bool result = WXApiConfigServices.UpdatePayConfig(config); if (!result) { throw new MyException("保存失败"); } return(Json(MyResult.Success())); } catch (MyException ex) { return(Json(MyResult.Error(ex.Message))); } catch (Exception ex) { ExceptionsServices.AddExceptions(ex, "保存微信API配置信息失败"); return(Json(MyResult.Error("保存失败"))); } }
/// <summary> /// 创建菜单 /// </summary> /// <param name="accessToken"></param> /// <param name="mainButton"></param> /// <returns></returns> public static bool CreateMenu(string companyId, string accessToken, MainButton mainButton) { ResError result = WxHttp.Post(WxUrl.CreateMenu.ToFormat(accessToken), mainButton); if (result.errcode == ResCode.请求成功) { return(true); } if (result.errcode == ResCode.获取accessToken时AppSecret错误或者accessToken无效) { WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(companyId); var newAccessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret, true); ResError newResult = WxHttp.Post(WxUrl.CreateMenu.ToFormat(newAccessToken), mainButton); if (newResult.errcode == ResCode.请求成功) { return(true); } } TxtLogServices.WriteTxtLogEx("WeiXinBase", "微信创建菜单错误!错误代码:{0},说明:{1}", (int)result.errcode, result.errmsg); return(false); }
/// <summary> /// 申请退款(V3接口) /// </summary> /// <param name="postData">请求参数</param> /// <param name="certPath">证书路径</param> /// <param name="certPwd">证书密码</param> public static bool Refund(string comapnyId, string transaction_Id, string out_trade_no, string total_fee, string refund_fee, string refundNo, string certpath) { TxtLogServices.WriteTxtLogEx("WeiXin_Request_Refund", "transaction_Id:{0};out_trade_no:{1};total_fee:{2};refund_fee:{3};refundNo:{4}", transaction_Id, out_trade_no, total_fee, refund_fee, refundNo); UnifiedPayModel model = UnifiedPayModel.CreateUnifiedModel(comapnyId); string postData = model.CreateOrderRefundXml(out_trade_no, transaction_Id, total_fee, refundNo, refund_fee); TxtLogServices.WriteTxtLogEx("WeiXin_Request_Refund", "postData xml:{0}", postData); WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(comapnyId); TxtLogServices.WriteTxtLogEx("WeiXin_Request_Refund", "config:{0}", config == null?"is null":"is not null"); if (config == null || string.IsNullOrWhiteSpace(config.CertPath) || string.IsNullOrWhiteSpace(config.CertPwd)) { throw new MyException("获取支付配置失败"); } string path = string.Format("{0}{1}", certpath, config.CertPath.TrimStart('/')); string url = WeiXinPayConst.WeiXin_Pay_UnifiedOrderRefundUrl; RefundMessage message = PostXmlResponse <RefundMessage>(url, postData, path, config.CertPwd); TxtLogServices.WriteTxtLogEx("WeiXin_Request_Refund", "OrderId:{0};return Xml:{1}", out_trade_no, message.ToXmlString()); return(message.Success); }
public ActionResult Get(string token, string signature, string timestamp, string nonce, string echostr) { try { WX_ApiConfig config = WXApiConfigServices.QueryByToKen(token); if (config == null || string.IsNullOrWhiteSpace(config.AppId) || string.IsNullOrWhiteSpace(config.AppSecret) || string.IsNullOrWhiteSpace(config.Domain) || string.IsNullOrWhiteSpace(config.Token)) { return(Content(string.Empty)); } if (WxService.CheckSignature(config.Token, timestamp, nonce, signature)) { return(Content(echostr)); } } catch (Exception ex) { ExceptionsServices.AddExceptions(ex, "微信公众账号提交验证失败", LogFrom.WeiXin); TxtLogServices.WriteTxtLogEx("Api_Get", "signature:{0};timestamp:{1};nonce:{2};echostr:{3}", signature, timestamp, nonce, echostr); } return(Content(string.Empty)); }
/// <summary> /// 发送图文消息 /// </summary> /// <param name="accessToken"></param> /// <param name="openId"></param> /// <param name="articles"></param> /// <returns></returns> public static bool SendNews(string companyId, string accessToken, string openId, List <Article> articles) { var data = new { touser = openId, msgtype = "news", news = new { articles = articles.Select(z => new { title = z.Title, description = z.Description, url = z.Url, picurl = z.PicUrl//图文消息的图片链接,支持JPG、PNG格式,较好的效果为大图640*320,小图80*80 }).ToList() } }; ResError result = WxHttp.Post(WxUrl.SendMsg.ToFormat(accessToken), data); if (result.errcode == ResCode.请求成功) { return(true); } if (result.errcode == ResCode.获取accessToken时AppSecret错误或者accessToken无效) { WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(companyId); var newAccessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret, true); ResError newResult = WxHttp.Post(WxUrl.SendMsg.ToFormat(newAccessToken), data); if (newResult.errcode == ResCode.请求成功) { return(true); } } TxtLogServices.WriteTxtLogEx("WeiXinBase", "发送图文消息错误!错误代码:{0},说明:{1}", (int)result.errcode, result.errmsg); return(false); }
public ActionResult SaveRecharge(decimal Amount) { try { BaseVillage village = VillageServices.QueryVillageByRecordId(SellerLoginUser.VID); if (village == null) { throw new MyException("获取小区信息失败"); } WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(village.CPID); if (config == null) { ExceptionsServices.AddExceptionToDbAndTxt("WeiXin_XFJM", "获取微信配置信息失败", "单位编号:" + village.CPID, LogFrom.WeiXin); return(RedirectToAction("Index", "ErrorPrompt", new { message = "获取微信配置信息失败!" })); } if (!config.Status) { ExceptionsServices.AddExceptionToDbAndTxt("WeiXin_XFJM", "该车场暂停使用微信支付", "单位编号:" + village.CPID, LogFrom.WeiXin); return(RedirectToAction("Index", "ErrorPrompt", new { message = "该车场暂停使用微信支付!" })); } if (config.CompanyID != WeiXinUser.CompanyID) { ExceptionsServices.AddExceptionToDbAndTxt("WeiXin_XFJM", "微信用户所属公众号和当前公众号不匹配,不能支付", string.Format("支付单位:{0},微信用户单位:{1}", config.CompanyID, WeiXinUser.CompanyID), LogFrom.WeiXin); return(RedirectToAction("Index", "ErrorPrompt", new { message = "微信用户所属公众号和当前公众号不匹配,不能支付!" })); } if (CurrLoginWeiXinApiConfig == null || config.CompanyID != CurrLoginWeiXinApiConfig.CompanyID) { string loginCompanyId = CurrLoginWeiXinApiConfig != null ? CurrLoginWeiXinApiConfig.CompanyID : string.Empty; ExceptionsServices.AddExceptionToDbAndTxt("WeiXin_XFJM", "车场所属公众号和当前公众号不匹配,不能支付", string.Format("支付单位:{0},微信用户单位:{1}", config.CompanyID, loginCompanyId), LogFrom.WeiXin); return(RedirectToAction("Index", "ErrorPrompt", new { message = "车场所属公众号和当前公众号不匹配,不能支付!" })); } OnlineOrder order = new OnlineOrder(); order.OrderID = IdGenerator.Instance.GetId(); order.InOutID = SellerLoginUser.SellerID; order.PKID = SellerLoginUser.SellerID; order.Status = OnlineOrderStatus.WaitPay; order.PayAccount = WeiXinUser.OpenID; order.Payer = WeiXinUser.OpenID; order.PKName = SellerLoginUser.SellerName; order.Amount = Amount; order.PayeeUser = config.SystemName; order.PayeeAccount = config.PartnerId; order.OrderType = OnlineOrderType.SellerRecharge; order.PaymentChannel = PaymentChannel.WeiXinPay; order.PayeeChannel = PaymentChannel.WeiXinPay; order.AccountID = WeiXinUser.AccountID; order.Amount = Amount; order.CardId = WeiXinUser.AccountID; order.CompanyID = config.CompanyID; order.OrderTime = DateTime.Now; order.Remark = "商家充值"; bool result = OnlineOrderServices.Create(order); if (!result) { throw new MyException("充值失败[保存订单失败]"); } return(RedirectToAction("SellerRechargePayment", "WeiXinPayment", new { orderId = order.OrderID })); } catch (MyException ex) { return(PageAlert("Index", "SellerRecharge", new { RemindUserContent = ex.Message })); } catch (Exception ex) { ExceptionsServices.AddExceptionToDbAndTxt("WeiXin_XFJM", "提交商家充值信息失败", ex, LogFrom.WeiXin); return(PageAlert("Index", "SellerRecharge", new { RemindUserContent = "提交商家充值信息失败" })); } }
public ActionResult SubmitParkingPaymentRequest(OnlineOrder model) { try { if (model.OrderSource == PayOrderSource.Platform) { //int interfaceOrderState = InterfaceOrderServices.OrderWhetherEffective(model.PayDetailID); int interfaceOrderState = InterfaceOrderServices.OrderWhetherEffective(model.PayDetailID, model.PKID, model.InOutID); if (interfaceOrderState != 1) { string msg = interfaceOrderState == 2 ? "重复支付" : "订单已失效"; string companyId = GetCompanyId(model.PKID, string.Empty, string.Empty); return(RedirectToAction("Index", "ErrorPrompt", new { message = msg, returnUrl = "/QRCode/Index?companyId=" + companyId + "" })); } } model.OrderID = IdGenerator.Instance.GetId(); model.Status = OnlineOrderStatus.WaitPay; model.OrderType = OnlineOrderType.ParkFee; model.Amount = model.Amount; BaseCompany company = CompanyServices.QueryByParkingId(model.PKID); if (company == null) { throw new MyException("获取单位信息失败"); } if (model.PaymentChannel == PaymentChannel.AliPay) { if (string.IsNullOrWhiteSpace(AliPayUserId)) { return(RedirectToAction("Index", "ErrorPrompt", new { message = "获取用户信息失败,请重新扫码进入" })); } AliPayApiConfig config = AliPayApiConfigServices.QueryAliPayConfig(company.CPID); if (config == null) { ExceptionsServices.AddExceptionToDbAndTxt("WeiXinPageError", "获取支付宝配置信息失败[0001]", "单位编号:" + company.CPID, LogFrom.WeiXin); return(RedirectToAction("Index", "ErrorPrompt", new { message = "获取支付宝配置信息失败!" })); } if (!config.Status) { ExceptionsServices.AddExceptionToDbAndTxt("WeiXinPageError", "该支付宝暂停使用", "单位编号:" + config.CompanyID, LogFrom.WeiXin); return(RedirectToAction("Index", "ErrorPrompt", new { message = "该车场暂停使用支付宝支付!" })); } if (model.OrderSource == PayOrderSource.Platform && (CurrLoginAliPayApiConfig == null || CurrLoginAliPayApiConfig.CompanyID != config.CompanyID)) { string loginCompanyId = CurrLoginAliPayApiConfig != null ? CurrLoginAliPayApiConfig.CompanyID : string.Empty; ExceptionsServices.AddExceptionToDbAndTxt("WeiXinPageError", "支付宝配置信息和当前支付宝配置信息不匹配,不能支付", string.Format("支付单位:{0},用户单位:{1}", config.CompanyID, loginCompanyId), LogFrom.WeiXin); if (CurrLoginAliPayApiConfig == null) { return(RedirectToAction("Index", "ErrorPrompt", new { message = "获取支付宝授权信息失败,请重试!" })); } return(RedirectToAction("Index", "ErrorPrompt", new { message = "支付宝配置信息和当前支付宝配置信息不匹配,不能支付!" })); } model.AccountID = string.Empty; model.CardId = string.Empty; model.PayeeChannel = PaymentChannel.AliPay; model.PaymentChannel = PaymentChannel.AliPay; model.PayeeUser = config.SystemName; model.PayeeAccount = config.PayeeAccount; model.Payer = AliPayUserId; model.PayAccount = AliPayUserId; model.CompanyID = config.CompanyID; } else { if (string.IsNullOrWhiteSpace(WeiXinOpenId)) { return(RedirectToAction("Index", "ErrorPrompt", new { message = "获取用户信息失败,请重新扫码进入" })); } WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(company.CPID); if (config == null) { ExceptionsServices.AddExceptionToDbAndTxt("WeiXinPageError", "获取微信配置信息失败", "单位编号:" + company.CPID, LogFrom.WeiXin); return(RedirectToAction("Index", "ErrorPrompt", new { message = "获取微信配置信息失败!" })); } if (!config.Status) { ExceptionsServices.AddExceptionToDbAndTxt("WeiXinPageError", "该车场暂停使用微信支付", "单位编号:" + company.CPID, LogFrom.WeiXin); return(RedirectToAction("Index", "ErrorPrompt", new { message = "该车场暂停使用微信支付!" })); } if (model.OrderSource == PayOrderSource.Platform && (CurrLoginWeiXinApiConfig == null || config.CompanyID != CurrLoginWeiXinApiConfig.CompanyID)) { string loginCompanyId = CurrLoginWeiXinApiConfig != null ? CurrLoginWeiXinApiConfig.CompanyID : string.Empty; ExceptionsServices.AddExceptionToDbAndTxt("WeiXinPageError", "车场所属公众号和当前公众号不匹配,不能支付", string.Format("支付单位:{0},微信用户单位:{1}", config.CompanyID, loginCompanyId), LogFrom.WeiXin); if (CurrLoginWeiXinApiConfig == null) { return(RedirectToAction("Index", "ErrorPrompt", new { message = "获取微信授权信息失败,请重试!" })); } return(RedirectToAction("Index", "ErrorPrompt", new { message = "车场所属公众号和当前公众号不匹配,不能支付!" })); } model.PayeeUser = config.SystemName; model.PayeeAccount = config.PartnerId; model.PayAccount = WeiXinOpenId; model.Payer = model.PayAccount; model.AccountID = model.AccountID; model.CardId = model.AccountID; model.PayeeChannel = PaymentChannel.WeiXinPay; model.PaymentChannel = PaymentChannel.WeiXinPay; model.CompanyID = config.CompanyID; } bool result = OnlineOrderServices.Create(model); if (!result) { throw new MyException("生成待缴费订单失败"); } switch (model.PaymentChannel) { case PaymentChannel.WeiXinPay: { return(RedirectToAction("ParkCarPayment", "WeiXinPayment", new { orderId = model.OrderID, source = 1 })); } case PaymentChannel.AliPay: { return(RedirectToAction("ParkCarPayment", "AliPayment", new { orderId = model.OrderID, source = 1 })); } default: throw new MyException("支付方式错误"); } } catch (MyException ex) { return(RedirectToAction("ComputeParkingFee", "QRCodeParkPayment", new { licensePlate = model.PlateNo, RemindUserContent = ex.Message })); } catch (Exception ex) { ExceptionsServices.AddExceptionToDbAndTxt("WeiXinPageError", "保存临停缴费订单失败", ex, LogFrom.WeiXin); return(RedirectToAction("ComputeParkingFee", "QRCodeParkPayment", new { licensePlate = model.PlateNo, RemindUserContent = "提交支付失败" })); } }
public ActionResult Post(string token, string signature, string timestamp, string nonce, string echostr) { WX_ApiConfig config = WXApiConfigServices.QueryByToKen(token); if (config == null || string.IsNullOrWhiteSpace(config.AppId) || string.IsNullOrWhiteSpace(config.AppSecret) || string.IsNullOrWhiteSpace(config.Domain) || string.IsNullOrWhiteSpace(config.Token)) { return(Content(string.Empty)); } //接收数据 //System.IO.StreamReader reader = new System.IO.StreamReader(Request.InputStream); //String xmlData = reader.ReadToEnd(); //XElement xdoc = XElement.Parse(xmlData); //解析XML //var toUserName = xdoc.Element("ToUserName").Value; //var fromUserName = xdoc.Element("FromUserName").Value; //var createTime = xdoc.Element("CreateTime").Value; //string key = xdoc.Element("EventKey").Value; //var content = xdoc.Element("Ticket").Value; //DateTime datatime = DateTime.Now; //if (!string.IsNullOrEmpty(key)) //{ //userin User = wxApi.GetNickname(wxApi.GetToken(config.AppId, config.AppSecret).Accesstoken, fromUserName); // string createSql = "insert into TgCount values('" + key + "','" + createTime + "','" + User.Nickname + "','" + toUserName + "','" + datatime + "')"; // using (DbOperator dboperator = ConnectionManager.CreateReadConnection()) // { // dboperator.ExecuteNonQuery(createSql, 30000); // } //} try { TxtLogServices.WriteTxtLogEx("Api_Post", "AppId:{0};AppSecret:{1};Domain:{2};Token:{3}", config.AppId, config.AppSecret, config.Domain, config.Token); if (!config.Status) { return(Content("该公众账号暂停使用,请稍后再试!")); } if (!WxService.CheckSignature(config.Token, timestamp, nonce, signature)) { return(Content(string.Empty)); } var conversation = new WeiXinConversation(token, Request.InputStream); try { TxtLogServices.WriteTxtLogEx("Api_Post_Request", conversation.RequestDocument.ToString()); //执行微信处理过程 conversation.Execute(); if (conversation.ResponseDocument != null) { TxtLogServices.WriteTxtLogEx("Api_Post_Response", conversation.ResponseDocument.ToString()); } } catch (Exception ex) { ExceptionsServices.AddExceptions(ex, "执行微信处理过程失败", LogFrom.WeiXin); TxtLogServices.WriteTxtLogEx("Api_Post_Error", ex); if (conversation.ResponseDocument != null) { TxtLogServices.WriteTxtLogEx("Api_Post_Error", conversation.ResponseDocument.ToString()); } } if (conversation.ResponseDocument != null) { //如果是微信位置推送则不回复 if (conversation.Request.MsgType == WReqType.Event) { WReqEventBase wreqevent = conversation.Request as WReqEventBase; if (wreqevent != null && wreqevent.Event == EventType.Location) { return(Content(string.Empty)); } } return(Content(conversation.ResponseDocument.ToString())); } } catch (Exception ex) { ExceptionsServices.AddExceptions(ex, "微信提交事件处理失败", LogFrom.WeiXin); TxtLogServices.WriteTxtLogEx("Api_Post_Error", ex); } return(Content(string.Empty)); }
public ActionResult SubmitBookingPayment(OnlineOrder model) { try { BaseCompany company = CompanyServices.QueryByParkingId(model.PKID); if (company == null) { throw new MyException("获取单位信息失败"); } WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(company.CPID); if (config == null) { ExceptionsServices.AddExceptionToDbAndTxt("WeiXinPageError", "获取微信配置信息失败", "单位编号:" + company.CPID, LogFrom.WeiXin); return(RedirectToAction("Index", "ErrorPrompt", new { message = "获取微信配置信息失败!" })); } if (!config.Status) { ExceptionsServices.AddExceptionToDbAndTxt("WeiXinPageError", "该车场暂停使用微信支付", "单位编号:" + company.CPID, LogFrom.WeiXin); return(RedirectToAction("Index", "ErrorPrompt", new { message = "该车场暂停使用微信支付!" })); } if (config.CompanyID != WeiXinUser.CompanyID) { ExceptionsServices.AddExceptionToDbAndTxt("WeiXinPageError", "微信用户所属公众号和当前公众号不匹配,不能支付", string.Format("支付单位:{0},微信用户单位:{1}", config.CompanyID, WeiXinUser.CompanyID), LogFrom.WeiXin); return(RedirectToAction("Index", "ErrorPrompt", new { message = "微信用户所属公众号和当前公众号不匹配,不能支付!" })); } if (CurrLoginWeiXinApiConfig == null || config.CompanyID != CurrLoginWeiXinApiConfig.CompanyID) { string loginCompanyId = CurrLoginWeiXinApiConfig != null ? CurrLoginWeiXinApiConfig.CompanyID : string.Empty; ExceptionsServices.AddExceptionToDbAndTxt("WeiXinPageError", "车场所属公众号和当前公众号不匹配,不能支付", string.Format("支付单位:{0},微信用户单位:{1}", config.CompanyID, loginCompanyId), LogFrom.WeiXin); return(RedirectToAction("Index", "ErrorPrompt", new { message = "车场所属公众号和当前公众号不匹配,不能支付!" })); } model.OrderID = IdGenerator.Instance.GetId(); model.Status = OnlineOrderStatus.WaitPay; model.PayAccount = WeiXinUser.OpenID; model.Payer = WeiXinUser.OpenID; model.PayeeUser = config.SystemName; model.OrderType = OnlineOrderType.PkBitBooking; model.AccountID = WeiXinUser.AccountID; model.OrderTime = DateTime.Now; model.CompanyID = config.CompanyID; bool result = OnlineOrderServices.Create(model); if (!result) { throw new MyException("生成车位预约订单失败"); } switch (model.PaymentChannel) { case PaymentChannel.WeiXinPay: { return(RedirectToAction("BookingBitNoPayment", "WeiXinPayment", new { orderId = model.OrderID })); } default: throw new MyException("支付方式错误"); } } catch (MyException ex) { return(PageAlert("SaveBooking", "ParkBitBooking", new { plateNo = model.PlateNo, parkingId = model.PKID, areaId = model.CardId, startTime = model.BookingStartTime, endTime = model.BookingEndTime, RemindUserContent = ex.Message })); } catch (Exception ex) { ExceptionsServices.AddExceptionToDbAndTxt("WeiXinWeb", "预约失败", ex, LogFrom.WeiXin); return(PageAlert("SaveBooking", "ParkBitBooking", new { plateNo = model.PlateNo, parkingId = model.PKID, areaId = model.CardId, startTime = model.BookingStartTime, endTime = model.BookingEndTime, RemindUserContent = "预约失败" })); } }