/// <summary> /// 初始化并设置微信公众号 /// </summary> /// <param name="idOrAppId">公众号的Id(itfc...)或微信的AppId(wx...)</param> /// <returns>返回微信接入实例本身</returns> public MessageLinkUp Initialize(string idOrAppId) { connect.Initialize(idOrAppId); weChatConfig = connect.WeChatConfig; wxcpt = new Tencent.WXBizMsgCrypt(weChatConfig.Token, weChatConfig.EncodingAESKey, weChatConfig.AppID); return(this); }
public ActionResult Category(string id) { ViewBag.isok = "OK"; ViewBag.Appid = WeChatConfig.GetKeyValue("appid"); ViewBag.Uri = WeChatConfig.GetKeyValue("shareurl"); noncestr = CommonMethod.GetCode(16); string jsapi_ticket = Js_sdk_Signature.IsExistjsapi_ticket(token.IsExistAccess_Token()); timestamp = DateTime.Now.Ticks.ToString().Substring(0, 10);; string url = Request.Url.ToString().Replace("#", ""); JssdkSignature = Js_sdk_Signature.GetjsSDK_Signature(noncestr, jsapi_ticket, timestamp, url); ViewBag.noncestr = noncestr; ViewBag.jsapi_ticket = jsapi_ticket; ViewBag.timestamp = timestamp; ViewBag.JssdkSignature = JssdkSignature; ViewBag.PageFlag = id; var sid = TypeParser.ToInt32(Request["sid"]); if (sid <= 0) { sid = 2; } ViewBag.SupplierID = sid; ViewBag.SupplierName = supplierB.Get(s => s.SUPPLIER_ID == sid).SUPPLIER_NAME; ViewBag.ProductList = VIEW_MST_PRD.ToListViewModel(prdB.GetListBy(p => p.CATE_ID == id && p.STATUS == true && p.ISCHECK == true, p => p.SEQ_NO)); var model = VIEW_MST_CATEGORY.ToViewModel(categoryB.Get(c => c.CATE_CD == id)); return(View(model)); }
/** * * 关闭订单 * @param WxPayData inputObj 提交给关闭订单API的参数 * @param int timeOut 接口超时时间 * @throws WxPayException * @return 成功时返回,其他抛异常 */ public static WxPayData CloseOrder(WeChatConfig wcf, WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/pay/closeorder"; //检测必填参数 if (!inputObj.IsSet("out_trade_no")) { throw new WxPayException("关闭订单接口中,out_trade_no必填!"); } inputObj.SetValue("appid", wcf.appId); //公众账号ID inputObj.SetValue("mch_id", wcf.mchId); //商户号 inputObj.SetValue("nonce_str", GenerateNonceStr()); //随机字符串 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); var start = DateTime.Now;//请求开始时间 string response = HttpService.Post(xml, url, false, timeOut); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds); WxPayData result = new WxPayData(wcf); result.FromXml(response); ReportCostTime(wcf, url, timeCost, result);//测速上报 return(result); }
/// <summary> /// 通过code得到openid /// </summary> /// <param name="code"></param> /// <param name="timeOut"></param> /// <returns></returns> public static string GetOpenId(WeChatConfig wcf, string code, int timeOut = 10) { string openid = string.Empty; string url = "https://api.weixin.qq.com/sns/jscode2session"; //检测必填参数 if (string.IsNullOrWhiteSpace(code)) { throw new WxPayException("小程序code转openid接口中,缺少必填参数code!"); } url += "?appid=" + wcf.appId; // WxPayConfig.APPID; url += "&secret=" + wcf.appSecret; // WxPayConfig.APPSECRET; url += "&js_code=" + code; url += "&grant_type=" + "authorization_code"; string jsonStr = HttpService.Get(url);//Get请求 // 解析JSON字符串 Dictionary <string, string> menu = jsonStr.JSDeserialize <Dictionary <string, string> >(); menu.TryGetValue("openid", out openid); return(openid); }
/** * * 转换短链接 * 该接口主要用于扫码原生支付模式一中的二维码链接转成短链接(weixin://wxpay/s/XXXXXX), * 减小二维码数据量,提升扫描速度和精确度。 * @param WxPayData inputObj 提交给转换短连接API的参数 * @param int timeOut 接口超时时间 * @throws WxPayException * @return 成功时返回,其他抛异常 */ public static WxPayData ShortUrl(WeChatConfig wcf, WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/tools/shorturl"; //检测必填参数 if (!inputObj.IsSet("long_url")) { throw new WxPayException("需要转换的URL,签名用原串,传输需URL encode!"); } inputObj.SetValue("appid", wcf.appId); //公众账号ID inputObj.SetValue("mch_id", wcf.mchId); //商户号 inputObj.SetValue("nonce_str", GenerateNonceStr()); //随机字符串 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); var start = DateTime.Now;//请求开始时间 Log.Debug("WxPayApi", "ShortUrl request : " + xml); string response = HttpService.Post(xml, url, false, timeOut); Log.Debug("WxPayApi", "ShortUrl response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds); WxPayData result = new WxPayData(wcf); result.FromXml(response); ReportCostTime(wcf, url, timeCost, result);//测速上报 return(result); }
public ActionResult ROrderDetail(string orderid) { //----- noncestr = CommonMethod.GetCode(16); string jsapi_ticket = Js_sdk_Signature.IsExistjsapi_ticket(WeChatConfig.IsExistAccess_Token2()); timestamp = DateTime.Now.Ticks.ToString().Substring(0, 10);; string url = Request.Url.ToString().Replace("#", ""); JssdkSignature = Js_sdk_Signature.GetjsSDK_Signature(noncestr, jsapi_ticket, timestamp, url); ViewBag.Appid = WeChatConfig.GetKeyValue("appid"); ViewBag.Uri = WeChatConfig.GetKeyValue("shareurl"); ViewBag.noncestr = noncestr; ViewBag.jsapi_ticket = jsapi_ticket; ViewBag.timestamp = timestamp; ViewBag.PageFlag = "PayOrder"; if (string.IsNullOrEmpty(CommonMethod.getCookie("userid")) || string.IsNullOrEmpty(CommonMethod.getCookie("openid"))) { return(Content("对不起,请登陆系统!")); } var order = orderB.Get(o => o.orderNum == orderid); if (order == null) { return(Content("对不起,这个订单是错误的!")); } return(View(VIEW_TG_order.ToViewModel(order))); }
/// <summary> /// 初始化一个<see cref="WeChat_AccessToken_RequestEntity"/>类型的实例 /// </summary> static WeChat_Authorization_RequestEntity() { var provider = Ioc.Create <IWeChatConfigProvider>(); provider.CheckNotNull(nameof(provider)); WeChatConfig = provider.GetConfigAsync().Result; }
/** * * 撤销订单API接口 * @param WxPayData inputObj 提交给撤销订单API接口的参数,out_trade_no和transaction_id必填一个 * @param int timeOut 接口超时时间 * @throws WxPayException * @return 成功时返回API调用结果,其他抛异常 */ public static WxPayData Reverse(WeChatConfig wcf, WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/secapi/pay/reverse"; //检测必填参数 if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id")) { throw new WxPayException("撤销订单API接口中,参数out_trade_no和transaction_id必须填写一个!"); } inputObj.SetValue("appid", wcf.appId); //公众账号ID inputObj.SetValue("mch_id", wcf.mchId); //商户号 inputObj.SetValue("nonce_str", GenerateNonceStr()); //随机字符串 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); var start = DateTime.Now;//请求开始时间 Log.Debug("WxPayApi", "Reverse request : " + xml); string response = HttpService.Post(xml, url, true, timeOut); Log.Debug("WxPayApi", "Reverse response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds); WxPayData result = new WxPayData(wcf); result.FromXml(response); ReportCostTime(wcf, url, timeCost, result);//测速上报 return(result); }
public static WeChatConfig GetWeChatConfig(string appName) { WxMastDataFactory factory = new WxMastDataFactory(); try { if (string.IsNullOrWhiteSpace(appName)) { throw new Exception("Param is null"); } WeChatConfig wxc = factory.GetWeChatConfig(appName); if (wxc == null) { throw new Exception("DAL.WeChat.WeChatPayFactory.GetPaySign()==null"); } return(wxc); } catch (Exception ex) { LogHelper.WriteLog(new Log() { message = ex.Message }, "GetWeChatConfig"); return(null); } }
/// <summary> /// 实例化微信消息管理实例,并指明操作的公众号 /// </summary> /// <param name="connectWeChat">微信接入基本操作对象</param> /// <param name="idOrAppId">公众号的AppId</param> public MessageLinkUp(IConnectLinkUp connectWeChat, string idOrAppId) { connect = connectWeChat; connect.Initialize(idOrAppId); weChatConfig = connect.WeChatConfig; wxcpt = new Tencent.WXBizMsgCrypt(weChatConfig.Token, weChatConfig.EncodingAESKey, weChatConfig.AppID); }
public async Task <MessageModel <string> > Put([FromBody] WeChatConfig obj) { await _WeChatConfigServices.Update(obj); return(new MessageModel <string> { success = true }); }
public WeChatConfig GetWeChatConfig(string appName) { string strSql = " SELECT * " + " FROM TBLWECHATCONFIG " + " WHERE APPNAME = '{0}' "; WeChatConfig wxc = SqlServerHelper.GetEntity <WeChatConfig>(SqlServerHelper.salesorderConn(), string.Format(strSql, appName)); return(wxc); }
public int UpdateFrom2() { //导入柠檬工坊基础数据 var session = this.OrchardServices.TransactionManager.GetSession(); var enjoyUser = new EnjoyUser() { Mobile = "13961576298", NickName = "稻草人", WxUser = null, Password = this.EncryptionService.Ciphertext("Window2008"), LastPassword = this.EncryptionService.Ciphertext("Window2008"), Profile = string.Empty, CreatedTime = DateTime.Now.ToUnixStampDateTime(), LastActivityTime = DateTime.Now.ToUnixStampDateTime() }; session.SaveOrUpdate(enjoyUser); var miniprogarm = new WeChatConfig("wx6a15c5888e292f99", "74c4c300a46b8c6eb8c79b3689065673", "1520961881", "EA62B75D5D3941C3A632B8F18C7B3575"); var official = new WeChatConfig("wx20da9548445a2ca7", "8fd877e51aa338a2c660e35d1f876e70", "1520961881", "EA62B75D5D3941C3A632B8F18C7B3575"); var payment = new Dictionary <string, string>(); payment.Add("1520961881", "EA62B75D5D3941C3A632B8F18C7B3575"); var merchant = new Merchant() { Address = "四川省眉山市东坡区东坡里商业水街2号楼14号", BrandName = "柠檬工坊", Code = "92511402MA6941EG0R", Contact = "刘丽群", CreateTime = DateTime.Now.ToUnixStampDateTime(), EnjoyUser = enjoyUser, LastActivityTime = DateTime.Now.ToUnixStampDateTime(), Miniprogram = miniprogarm.SerializeToJson(), Official = official.SerializeToJson(), Payment = payment.SerializeToJson(), Mobile = "13890397856" }; session.SaveOrUpdate(merchant); var shop = new Shop() { Address = merchant.Address, Pid = 491431822, LastActivityTime = DateTime.Now.ToUnixStampDateTime(), Leader = "刘丽群", Merchant = merchant, ShopName = "柠檬工坊东坡店" }; session.SaveOrUpdate(shop); return(3); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); // Configure CORS for UI services.AddCors(options => options.AddPolicy( DefaultCorsPolicyName, builder => builder .WithOrigins( Configuration["App:CorsOrigins"] .Split(",", StringSplitOptions.RemoveEmptyEntries) .Select(o => o.RemovePostFix("/")) .ToArray() ) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials() )); services.AddWeChatCore(Configuration, options => { //options.WeChatConfigFunc = new WeChatConfig(Configuration["App:AppId"], Configuration["App:AppSecret"]); options.WeChatConfig = WeChatConfig.GetOptionsFromConfig(Configuration, "WeChatPlateForm:MiniProgram"); options.UseCache = WeChatConstants.UseMSCache; options.RefreshTimeSpan = 1; }); #region DI services.AddTransient <IImgSecApp, ImgSecApp>(); services.AddTransient <IUserAccountApp, UserAccountApp>(); #endregion services.AddSwaggerDocument(document => { document.DocumentName = "NSwag"; #region OAuth2 #endregion // Post process the generated document document.PostProcess = d => { d.Info.Title = "WeiXin"; d.Info.Description = "Api文档"; }; }); // Register a OpenAPI v3.0 document generator services.AddOpenApiDocument( document => document.DocumentName = "OpenAPI"); }
/// 获取预payid /// <summary> /// 获取预payid /// </summary> /// <returns></returns> public string GetPrepayId() { this.parameters.Add("sign", GetSign(this.parameters)); string xml = MakePostXml(); string content = Common.Tools.GetPage(unifiedorderURL, xml); XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(content); return(WeChatConfig.GetXMLstrByKey("prepay_id", xmldoc)); }
public ActionResult ProductDetail(string id) { ViewBag.Appid = WeChatConfig.GetKeyValue("appid"); ViewBag.Uri = WeChatConfig.GetKeyValue("shareurl"); noncestr = CommonMethod.GetCode(16); string jsapi_ticket = Js_sdk_Signature.IsExistjsapi_ticket(token.IsExistAccess_Token()); timestamp = DateTime.Now.Ticks.ToString().Substring(0, 10);; string url = Request.Url.ToString().Replace("#", ""); JssdkSignature = Js_sdk_Signature.GetjsSDK_Signature(noncestr, jsapi_ticket, timestamp, url); ViewBag.noncestr = noncestr; ViewBag.jsapi_ticket = jsapi_ticket; ViewBag.timestamp = timestamp; ViewBag.JssdkSignature = JssdkSignature; var userid = CommonMethod.getCookie("userid"); var openid = CommonMethod.getCookie("openid"); ViewBag.userName = ""; ViewBag.userTel = ""; if (!string.IsNullOrEmpty(userid) && !string.IsNullOrEmpty(openid)) { var user = VIEW_YX_weiUser.ToViewModel(weiUserM.GetModelWithOutTrace(u => u.openid == openid)); if (user != null) { ViewBag.userName = user.userRelname; ViewBag.userTel = user.userTel; } } var sid = TypeParser.ToInt32(Request["sid"]); if (sid <= 0) { sid = 2; } ViewBag.SupplierID = sid; var supplier = supplierB.Get(s => s.SUPPLIER_ID == sid); ViewBag.SupplierName = supplier.SUPPLIER_NAME; ViewBag.Address = supplier.ADDRESS; ViewBag.Tel = supplier.TEL; var model = VIEW_MST_PRD.ToViewModel(prdB.Get(p => p.PRD_CD == id)); ViewBag.ImgList = VIEW_MST_PRD_IMG.ToListViewModel(prdimgB.GetListBy(pm => pm.PRD_CD == id)); ViewBag.AM = sysrefB.GetListBy(s => s.REF_TYPE == model.CATE_ID && s.REF_PARAM.Contains("AM_"), s => s.REF_SEQ); ViewBag.PM = sysrefB.GetListBy(s => s.REF_TYPE == model.CATE_ID && s.REF_PARAM.Contains("PM_"), s => s.REF_SEQ); ViewBag.PageFlag = model.CATE_ID; return(View(model)); }
public WeChatPayFactory(string appName = null) { if (!string.IsNullOrWhiteSpace(appName)) { //string strSql = " SELECT * " + // " FROM TBLWECHATCONFIG " + // " WHERE APPNAME = '{0}' "; //wcf = SqlServerHelper.GetEntity<WeChatConfig>(SqlServerHelper.salesorderConn, string.Format(strSql, appName)); wcf = (new WxMastDataFactory()).GetWeChatConfig(appName); } }
/** * * 申请退款 * @param WxPayData inputObj 提交给申请退款API的参数 * @param int timeOut 超时时间 * @throws WxPayException * @return 成功时返回接口调用结果,其他抛异常 */ public static WxPayData Refund(WeChatConfig wcf, WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/secapi/pay/refund"; //检测必填参数 if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id")) { throw new WxPayException("退款申请接口中,out_trade_no、transaction_id至少填一个!"); } else if (!inputObj.IsSet("out_refund_no")) { throw new WxPayException("退款申请接口中,缺少必填参数out_refund_no!"); } else if (!inputObj.IsSet("total_fee")) { throw new WxPayException("退款申请接口中,缺少必填参数total_fee!"); } else if (!inputObj.IsSet("refund_fee")) { throw new WxPayException("退款申请接口中,缺少必填参数refund_fee!"); } else if (!inputObj.IsSet("op_user_id")) { throw new WxPayException("退款申请接口中,缺少必填参数op_user_id!"); } inputObj.SetValue("appid", wcf.appId); //公众账号ID inputObj.SetValue("mch_id", wcf.mchId); //商户号 inputObj.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", "")); //随机字符串 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); var start = DateTime.Now; Log.Debug("WxPayApi", "Refund request : " + xml); string response = HttpService.Post(xml, url, true, timeOut);//调用HTTP通信接口提交数据到API Log.Debug("WxPayApi", "Refund response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时 //将xml格式的结果转换为对象以返回 WxPayData result = new WxPayData(wcf); result.FromXml(response); ReportCostTime(wcf, url, timeCost, result);//测速上报 return(result); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); var weChatConfig = Configuration.GetSection("WeChatConfig"); WeChatConfig.InitConfig(weChatConfig["AppId"], weChatConfig["AppSecret"], weChatConfig["Token"]); BotConfig.InitConfig(Configuration.GetSection("BotConfig")["SecretKey"]); }
/** * 提交被扫支付API * 收银员使用扫码设备读取微信用户刷卡授权码以后,二维码或条码信息传送至商户收银台, * 由商户收银台或者商户后台调用该接口发起支付。 * @param WxPayData inputObj 提交给被扫支付API的参数 * @param int timeOut 超时时间 * @throws WxPayException * @return 成功时返回调用结果,其他抛异常 */ public static WxPayData Micropay(WeChatConfig wcf, WxPayData inputObj, int timeOut = 10) { string url = "https://api.mch.weixin.qq.com/pay/micropay"; //检测必填参数 if (!inputObj.IsSet("body")) { throw new WxPayException("提交被扫支付API接口中,缺少必填参数body!"); } else if (!inputObj.IsSet("out_trade_no")) { throw new WxPayException("提交被扫支付API接口中,缺少必填参数out_trade_no!"); } else if (!inputObj.IsSet("total_fee")) { throw new WxPayException("提交被扫支付API接口中,缺少必填参数total_fee!"); } else if (!inputObj.IsSet("auth_code")) { throw new WxPayException("提交被扫支付API接口中,缺少必填参数auth_code!"); } inputObj.SetValue("spbill_create_ip", WxPayConfig.IP); //终端ip inputObj.SetValue("appid", wcf.appId); //公众账号ID inputObj.SetValue("mch_id", wcf.mchId); //商户号 inputObj.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", "")); //随机字符串 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); var start = DateTime.Now;//请求开始时间 Log.Debug("WxPayApi", "MicroPay request : " + xml); string response = HttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口以提交数据到API Log.Debug("WxPayApi", "MicroPay response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时 //将xml格式的结果转换为对象以返回 WxPayData result = new WxPayData(wcf); result.FromXml(response); ReportCostTime(wcf, url, timeCost, result);//测速上报 return(result); }
/// <summary> /// 通过AppId + AppSecret得到access_token(更新秒数根据获取access_token时的回传值而定) /// </summary> /// <param name="wcf"></param> /// <param name="isNew">判断值为"isNew"时强制更新access_token</param> /// <returns></returns> public static string GetAccessToken(WeChatConfig wcf, string isNew = "") { WxAccessToken accessTokenObj = lstAccessTokenObj.Where(r => wcf.appName.Equals(r.appName)).FirstOrDefault(); if ("isnew".Equals(isNew.ToLower()) || accessTokenObj == null || string.IsNullOrWhiteSpace(accessTokenObj.access_token) || CheckExpireTime(accessTokenObj)) { /***获取新的access_token***/ string access_token = string.Empty; string expires_in = string.Empty; string url = "https://api.weixin.qq.com/cgi-bin/token"; url += "?grant_type=client_credential"; url += "&appid=" + wcf.appId; url += "&secret=" + wcf.appSecret; //Get请求 string jsonStr = HttpService.Get(url); // 解析JSON字符串 Dictionary <string, string> menu = jsonStr.JSDeserialize <Dictionary <string, string> >(); menu.TryGetValue("access_token", out access_token); menu.TryGetValue("expires_in", out expires_in); // 考虑到获取access_token可能存在网络延迟,这里重新获取一次当前时间 DateTime nowTime = DateTime.Now; WxAccessToken at = new WxAccessToken { // AppName appName = wcf.appName, // access_token access_token = access_token, // XX秒后过期 expires_in = expires_in, // 更新时间 updateTime = nowTime }; accessTokenObj = at; // 更新access_token列表中的值 UpdateAccessToken(at); } return(accessTokenObj.access_token); }
/** * * 测速上报接口实现 * @param WxPayData inputObj 提交给测速上报接口的参数 * @param int timeOut 测速上报接口超时时间 * @throws WxPayException * @return 成功时返回测速上报接口返回的结果,其他抛异常 */ public static WxPayData Report(WeChatConfig wcf, WxPayData inputObj, int timeOut = 1) { string url = "https://api.mch.weixin.qq.com/payitil/report"; //检测必填参数 if (!inputObj.IsSet("interface_url")) { throw new WxPayException("接口URL,缺少必填参数interface_url!"); } if (!inputObj.IsSet("return_code")) { throw new WxPayException("返回状态码,缺少必填参数return_code!"); } if (!inputObj.IsSet("result_code")) { throw new WxPayException("业务结果,缺少必填参数result_code!"); } if (!inputObj.IsSet("user_ip")) { throw new WxPayException("访问接口IP,缺少必填参数user_ip!"); } if (!inputObj.IsSet("execute_time_")) { throw new WxPayException("接口耗时,缺少必填参数execute_time_!"); } inputObj.SetValue("appid", wcf.appId); //公众账号ID inputObj.SetValue("mch_id", wcf.mchId); //商户号 inputObj.SetValue("user_ip", WxPayConfig.IP); //终端ip inputObj.SetValue("time", DateTime.Now.ToString("yyyyMMddHHmmss")); //商户上报时间 inputObj.SetValue("nonce_str", GenerateNonceStr()); //随机字符串 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); Log.Info("WxPayApi", "Report request : " + xml); string response = HttpService.Post(xml, url, false, timeOut); Log.Info("WxPayApi", "Report response : " + response); WxPayData result = new WxPayData(wcf); result.FromXml(response); return(result); }
/// <summary> /// 接收从微信支付后台发送过来的数据并验证签名 /// </summary> /// <returns>微信支付后台返回的数据</returns> public WxPayData GetNotifyData(WeChatConfig wcf) { //接收从微信后台POST过来的数据 System.IO.Stream s = page.Request.InputStream; int count = 0; byte[] buffer = new byte[1024]; StringBuilder builder = new StringBuilder(); while ((count = s.Read(buffer, 0, 1024)) > 0) { builder.Append(Encoding.UTF8.GetString(buffer, 0, count)); } s.Flush(); s.Close(); s.Dispose(); Log.Info(this.GetType().ToString(), "Receive data from WeChat : " + builder.ToString()); //转换数据格式并验证签名 WxPayData data = new WxPayData(wcf); try { data.FromXml(builder.ToString()); } catch (WxPayException ex) { //若签名错误,则立即返回结果给微信支付后台 WxPayData res = new WxPayData(wcf); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", ex.Message); Log.Error(this.GetType().ToString(), "Sign check error : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } Log.Info(this.GetType().ToString(), "Check sign success"); return(data); }
/** * * 查询退款 * 提交退款申请后,通过该接口查询退款状态。退款有一定延时, * 用零钱支付的退款20分钟内到账,银行卡支付的退款3个工作日后重新查询退款状态。 * out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个 * @param WxPayData inputObj 提交给查询退款API的参数 * @param int timeOut 接口超时时间 * @throws WxPayException * @return 成功时返回,其他抛异常 */ public static WxPayData RefundQuery(WeChatConfig wcf, WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/pay/refundquery"; //检测必填参数 if (!inputObj.IsSet("out_refund_no") && !inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id") && !inputObj.IsSet("refund_id")) { throw new WxPayException("退款查询接口中,out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个!"); } inputObj.SetValue("appid", wcf.appId); //公众账号ID inputObj.SetValue("mch_id", wcf.mchId); //商户号 inputObj.SetValue("nonce_str", GenerateNonceStr()); //随机字符串 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); var start = DateTime.Now;//请求开始时间 Log.Debug("WxPayApi", "RefundQuery request : " + xml); string response = HttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口以提交数据到API Log.Debug("WxPayApi", "RefundQuery response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时 //将xml格式的结果转换为对象以返回 WxPayData result = new WxPayData(wcf); result.FromXml(response); ReportCostTime(wcf, url, timeCost, result);//测速上报 return(result); }
/** * 下载对账单 * @param WxPayData inputObj 提交给下载对账单API的参数 * @param int timeOut 接口超时时间 * @throws WxPayException * @return 成功时返回,其他抛异常 */ public static WxPayData DownloadBill(WeChatConfig wcf, WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/pay/downloadbill"; //检测必填参数 if (!inputObj.IsSet("bill_date")) { throw new WxPayException("对账单接口中,缺少必填参数bill_date!"); } inputObj.SetValue("appid", wcf.appId); //公众账号ID inputObj.SetValue("mch_id", wcf.mchId); //商户号 inputObj.SetValue("nonce_str", GenerateNonceStr()); //随机字符串 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); Log.Debug("WxPayApi", "DownloadBill request : " + xml); string response = HttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口以提交数据到API Log.Debug("WxPayApi", "DownloadBill result : " + response); WxPayData result = new WxPayData(wcf); //若接口调用失败会返回xml格式的结果 if (response.Substring(0, 5) == "<xml>") { result.FromXml(response); } //接口调用成功则返回非xml格式的数据 else { result.SetValue("result", response); } return(result); }
public static string certPwd = ""; //GetKeyValue("mchid");//证书密码 及 商户平台商户号 初始密码 可以修改 public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; Appsecret = WeChatConfig.GetKeyValue("appsecret"); AppId = WeChatConfig.GetKeyValue("appid"); apisecret = WeChatConfig.GetKeyValue("apisecret"); URLToken = WeChatConfig.GetKeyValue("token"); try { if (HttpContext.Current.Request.HttpMethod.ToUpper() == "GET") { if (!AccessTokenContainer.CheckRegistered(AppId)) { AccessTokenContainer.Register(AppId, Appsecret); } Auth(); //微信接入的测试 成为开发者第一步 } if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST") { if (!AccessTokenContainer.CheckRegistered(AppId)) { AccessTokenContainer.Register(AppId, Appsecret); } responseMsg(); } } catch (Exception ex) { LogHelper.WriteLog("一般处理程序入口错误:", ex); } // context.Response.Write("Hello World"); }
public ActionResult successPay(string ordernum) { var status = false; var openid = CommonMethod.getCookie("openid"); var userid = CommonMethod.getCookie("userid"); var type = Request["paytype"]; var user = weiUserM.GetModelWithOutTrace(u => u.userNum == userid && u.openid == openid); if (user == null) { return(Content("对不起,请登陆系统!")); } var order = orderB.GetModelWithOutTrace(o => o.orderNum == ordernum); if (order == null) { return(Content("对不起,这个订单是错误的!")); } if (string.IsNullOrEmpty(type)) { //添加交易记录 TG_transactionLog transactionlog = new TG_transactionLog(); transactionlog.userId = userid; transactionlog.openid = openid; transactionlog.tranCate = 0; transactionlog.CateName = "微信消费"; transactionlog.tranMoney = order.yunPrice; transactionlog.tranContent = "微信消费(订单号:" + ordernum + ")消费:" + order.total_fee + " 元,预付:" + order.yunPrice + " 元"; transactionlog.orderNum = ordernum; transactionlog.remark4 = "1001"; transactionlog.AddTime = DateTime.Now; transactionlogB.Add(transactionlog); YX_sysNews sysnew = new YX_sysNews(); sysnew.userid = userid; sysnew.orderId = ordernum; sysnew.newsCate = "订单提醒"; sysnew.newsContent = "用户微信支付成功"; sysnew.newsState = 0; sysnew.Addtime = DateTime.Now; OperateContext.Current.BLLSession.IYX_sysNews_MANAGER.Add(sysnew); Common.Tools.GetPage("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + WeChatConfig.IsExistAccess_Token2(), WeChatConfig.GetSubcribePostData(openid, transactionlog.tranContent)); } else if (user.isfenxiao >= 1 && user.userYongJin > order.total_fee) { order.ssh_status = 3; order.ispay = 3; order.yunPrice = order.total_fee; order.payTime = DateTime.Now; orderB.Modify(order, "yunPrice", "payTime", "ispay", "ssh_status"); //添加交易记录 TG_transactionLog transactionlog = new TG_transactionLog(); transactionlog.userId = userid; transactionlog.openid = openid; transactionlog.tranCate = 0; transactionlog.CateName = "微信消费"; transactionlog.tranMoney = order.total_fee; transactionlog.tranContent = "会员微信消费(订单号:" + ordernum + ")消费:" + order.total_fee + " 元"; transactionlog.orderNum = ordernum; transactionlog.remark4 = "1002"; transactionlog.AddTime = DateTime.Now; transactionlogB.Add(transactionlog); user.userYongJin = user.userYongJin - order.total_fee; weiUserM.Modify(user, "userYongJin"); YX_sysNews sysnew = new YX_sysNews(); sysnew.userid = userid; sysnew.orderId = ordernum; sysnew.newsCate = "订单提醒"; sysnew.newsContent = "用户微信支付成功"; sysnew.newsState = 0; sysnew.Addtime = DateTime.Now; OperateContext.Current.BLLSession.IYX_sysNews_MANAGER.Add(sysnew); Common.Tools.GetPage("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + WeChatConfig.IsExistAccess_Token2(), WeChatConfig.GetSubcribePostData(openid, transactionlog.tranContent)); } else { } List <string> openids = new List <string>() { "oJUBAv7TVJBowlpJs58qBvCNCrAc", "oJUBAv1jDW_8IQyyvYyTjW2Q6o3w", "oJUBAv9bmEB2mFMSZyLkZBaTK540", "oJUBAv3rjppIvGenkn3h1MIo4wts", "oJUBAv7XiorX2muQXNft5ChU1OCk", "oJUBAv2Omhudt9cyqG_f2A1xMhUA" }; foreach (var item in openids) { Common.Tools.GetPage("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + WeChatConfig.IsExistAccess_Token2(), WeChatConfig.GetSubcribePostData(item, "用户: " + user.userRelname + " 已成功预约。\n预约订单号:" + order.orderNum + "\n预约时间:" + order.remark4 + " " + order.remark5 + "\n 联系电话:" + user.userTel)); } return(Redirect("/aoshacar/OrderDetail?orderid=" + ordernum)); }
public ActionResult PayOrder(string orderid) { ViewBag.PageFlag = "PayOrder"; var openid = CommonMethod.getCookie("openid"); var userid = CommonMethod.getCookie("userid"); var user = weiUserM.GetModelWithOutTrace(u => u.userNum == userid && u.openid == openid); if (user == null) { return(Content("对不起,请登陆系统!")); } ViewBag.UserType = user.isfenxiao; ViewBag.userYongJin = user.userYongJin; ViewBag.Userid = userid; ViewBag.Openid = openid; var order = orderB.Get(o => o.orderNum == orderid); if (order == null) { return(Content("对不起,这个订单是错误的!")); } //----- noncestr = CommonMethod.GetCode(16); string jsapi_ticket = Js_sdk_Signature.IsExistjsapi_ticket(WeChatConfig.IsExistAccess_Token2()); timestamp = DateTime.Now.Ticks.ToString().Substring(0, 10);; string url = Request.Url.ToString().Replace("#", ""); JssdkSignature = Js_sdk_Signature.GetjsSDK_Signature(noncestr, jsapi_ticket, timestamp, url); ViewBag.Appid = WeChatConfig.GetKeyValue("appid"); ViewBag.Uri = WeChatConfig.GetKeyValue("shareurl"); ViewBag.noncestr = noncestr; ViewBag.jsapi_ticket = jsapi_ticket; ViewBag.timestamp = timestamp; //微信支付代码 // //httpContext var packageReqHandler = new RequestHandler(HttpContext); packageReqHandler.Init(); //时间戳 payTimeSamp = Senparc.Weixin.MP.TenPayLibV3.TenPayV3Util.GetTimestamp(); //随机字符串 sj = CommonMethod.GetCode(16) + "_" + userid; //设置参数 packageReqHandler.SetParameter("body", "商城-购买支付"); //商品信息 127字符 packageReqHandler.SetParameter("appid", PayConfig.AppId); packageReqHandler.SetParameter("mch_id", PayConfig.MchId); packageReqHandler.SetParameter("nonce_str", sj); packageReqHandler.SetParameter("notify_url", PayConfig.NotifyUrl); packageReqHandler.SetParameter("openid", openid); packageReqHandler.SetParameter("out_trade_no", orderid + "_" + CommonMethod.GetCode(4)); //商家订单号 packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress); //用户的公网ip,不是商户服务器IP packageReqHandler.SetParameter("total_fee", (Convert.ToDouble(order.yunPrice) * 100).ToString()); //商品金额,以分为单位(money * 100).ToString() packageReqHandler.SetParameter("trade_type", "JSAPI"); packageReqHandler.SetParameter("attach", CommonMethod.GetCode(28)); //自定义参数 127字符 string sign = packageReqHandler.CreateMd5Sign("key", PayConfig.AppKey); //第一次签名结果 #region 获取package包====================== packageReqHandler.SetParameter("sign", sign); string data = packageReqHandler.ParseXML();//支付发送的数据 XML格式 string prepayXml = Senparc.Weixin.MP.AdvancedAPIs.TenPayV3.Unifiedorder(data); //string prepayXml = WeiXin.GetPage("https://api.mch.weixin.qq.com/pay/unifiedorder", data); var xdoc = new XmlDocument(); xdoc.LoadXml(prepayXml); XmlNode xn = xdoc.SelectSingleNode("xml"); LogHelper.WriteLog(prepayXml); try { string PrepayId = WeChatConfig.GetXMLstrByKey("prepay_id", xdoc); Package = string.Format("prepay_id={0}", PrepayId); LogHelper.WriteLog(Package); } catch (Exception ex) { LogHelper.WriteLog(ex.ToString()); Package = string.Format("prepay_id={0}", ""); } #endregion #region 设置支付参数 输出页面 该部分参数请勿随意修改 ============== var paySignReqHandler = new RequestHandler(HttpContext); paySignReqHandler.SetParameter("appId", PayConfig.AppId); paySignReqHandler.SetParameter("timeStamp", payTimeSamp); paySignReqHandler.SetParameter("nonceStr", sj); paySignReqHandler.SetParameter("package", Package); paySignReqHandler.SetParameter("signType", "MD5"); PaySign = paySignReqHandler.CreateMd5Sign("key", PayConfig.AppKey); #endregion //--------END ViewBag.payTimeSamp = payTimeSamp; ViewBag.sj = sj; ViewBag.Package = Package; ViewBag.PaySign = PaySign; return(View(VIEW_TG_order.ToViewModel(order))); }
public ActionResult UserMain() { ViewBag.PageFlag = "UserMain"; ViewBag.isok = "OK"; ViewBag.Appid = WeChatConfig.GetKeyValue("appid"); ViewBag.Uri = WeChatConfig.GetKeyValue("shareurl"); noncestr = CommonMethod.GetCode(16); string jsapi_ticket = Js_sdk_Signature.IsExistjsapi_ticket(token.IsExistAccess_Token()); timestamp = DateTime.Now.Ticks.ToString().Substring(0, 10);; string url = Request.Url.ToString().Replace("#", ""); JssdkSignature = Js_sdk_Signature.GetjsSDK_Signature(noncestr, jsapi_ticket, timestamp, url); ViewBag.noncestr = noncestr; ViewBag.jsapi_ticket = jsapi_ticket; ViewBag.timestamp = timestamp; openid = CommonMethod.getCookie("openid"); userid = CommonMethod.getCookie("userid"); if (string.IsNullOrEmpty(openid)) { //根据授权 获取openid //根据授权 获取用户的openid string code = Request.QueryString["code"];//获取授权code LogHelper.WriteLog("//////////////////////////////////////////////////////////////////////////////////"); LogHelper.WriteLog("code:" + code); if (string.IsNullOrEmpty(code)) { string codeurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx242aa47391c159f6&redirect_uri=http://www.aoshacar.com/AoShaCar/userMain&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect"; Response.Redirect(codeurl); } else { string openIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WeChatConfig.GetKeyValue("appid") + "&secret=" + WeChatConfig.GetKeyValue("appsecret") + "&code=" + code + "&grant_type=authorization_code"; string content = Tools.GetPage(openIdUrl, ""); openid = Tools.GetJsonValue(content, "openid");//根据授权 获取当前人的openid } } var model = VIEW_YX_weiUser.ToViewModel(weiUserM.GetModelWithOutTrace(u => u.openid == openid)); if (model != null) { CommonMethod.delCookie("openid"); CommonMethod.delCookie("userid"); CommonMethod.setCookie("openid", openid, 1); CommonMethod.setCookie("userid", model.userNum, 1); ViewBag.nickname = model.nickname; ViewBag.headimgurl = model.headimgurl; } else { Senparc.Weixin.MP.AdvancedAPIs.User.UserInfoJson dic = Senparc.Weixin.MP.AdvancedAPIs.UserApi.Info(token.IsExistAccess_Token(), openid); //LogHelper.WriteLog("XXXXXXXXXXX:" + openid); if (dic != null) { ViewBag.nickname = dic.nickname; ViewBag.headimgurl = dic.headimgurl; } model = new MODEL.ViewModel.VIEW_YX_weiUser(); model.subscribe = dic.subscribe; model.openid = dic.openid; model.nickname = dic.nickname; model.sex = dic.sex; model.U_language = dic.language; model.city = dic.city; model.province = dic.province; model.country = dic.country; model.headimgurl = dic.headimgurl; model.subscribe_time = DateTime.Now; model.userSex = dic.sex == 2 ? "女" : "男"; model.userNum = Common.Tools.Get8Digits(); model.F_id = 0; model.isfenxiao = 0; model.userMoney = 0; model.userYongJin = 0; weiUserM.Add(VIEW_YX_weiUser.ToEntity(model)); } ViewBag.UserType = ConfigSettings.GetSysConfigValue("USERTYPE", model.isfenxiao.ToString()); return(View(model)); }
public ActionResult Index() { ViewBag.PageFlag = "Index"; if (string.IsNullOrEmpty(CommonMethod.getCookie("userid")) || string.IsNullOrEmpty(CommonMethod.getCookie("openid"))) { //CommonMethod.delCookie("userid"); //登陆 string code = Request.QueryString["code"];//获取授权code if (!string.IsNullOrEmpty(code)) { string openIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WeChatConfig.GetKeyValue("appid") + "&secret=" + WeChatConfig.GetKeyValue("appsecret") + "&code=" + code + "&grant_type=authorization_code"; string content = Tools.GetPage(openIdUrl, ""); openid = Tools.GetJsonValue(content, "openid");//根据授权 获取当前人的openid var model = weiUserM.GetModelWithOutTrace(u => u.openid == openid); if (model != null) { CommonMethod.delCookie("openid"); CommonMethod.delCookie("userid"); CommonMethod.setCookie("openid", openid, 1); CommonMethod.setCookie("userid", model.userNum, 1); } } else { string codeurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx242aa47391c159f6&redirect_uri=http://www.aoshacar.com/AoShaCar/Index&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect"; Response.Redirect(codeurl); } //end } ViewBag.PageFlag = "Index"; var sid = TypeParser.ToInt32(Request["sid"]); if (sid <= 0) { sid = 2; } ViewBag.SupplierID = sid; ViewBag.SupplierName = supplierB.Get(s => s.SUPPLIER_ID == sid).SUPPLIER_NAME; ViewBag.CategoryList = VIEW_MST_CATEGORY.ToListViewModel(categoryB.GetListBy(c => c.ACTIVE == true)); ViewBag.ProductList = VIEW_MST_PRD.ToListViewModel(prdB.GetListBy(p => p.ISCHECK == true && p.STATUS == true && p.ISHOT == true, p => p.SEQ_NO)); return(View()); }