public static void Init(IPlugin plugin) { app = plugin; PluginAttr = plugin.GetAttribute(); initCfg(PluginAttr); InitWeixin(PluginAttr.Settings); //提供微信支付信息 var weixinPay_PartnerId = PluginAttr.Settings["WeixinPay_PartnerId"]; var weixinPay_Key = PluginAttr.Settings["WeixinPay_Key"]; var weixinPay_AppId = PluginAttr.Settings["WeixinPay_AppId"]; var weixinPay_AppKey = PluginAttr.Settings["WeixinPay_AppKey"]; var weixinPay_TenpayNotify = PluginAttr.Settings["WeixinPay_TenpayNotify"]; var tenPayV3_MchId = PluginAttr.Settings["TenPayV3_MchId"]; var tenPayV3_Key = PluginAttr.Settings["TenPayV3_Key"]; var tenPayV3_AppId = PluginAttr.Settings["TenPayV3_AppId"]; var tenPayV3_AppSecret = PluginAttr.Settings["TenPayV3_AppSecret"]; var tenPayV3_TenpayNotify = PluginAttr.Settings["TenPayV3_TenpayNotify"]; var weixinPayInfo = new TenPayInfo(weixinPay_PartnerId, weixinPay_Key, weixinPay_AppId, weixinPay_AppKey, weixinPay_TenpayNotify); TenPayInfoCollection.Register(weixinPayInfo); var tenPayV3Info = new TenPayV3Info(tenPayV3_AppId, tenPayV3_AppSecret, tenPayV3_MchId, tenPayV3_Key, tenPayV3_TenpayNotify); TenPayV3InfoCollection.Register(tenPayV3Info); }
public async Task <BaseResultModel> RefundAsync(string outTradeNo, string outRefundNo, int totalFee, int refundFee, SystemConfigs tencentparam, string msg = null) { BaseResultModel model = new BaseResultModel(); try { TenPayV3Info TenPayV3Info = new TenPayV3Info(tencentparam.AppID, tencentparam.AppSecret, tencentparam.TenPayMchId, tencentparam.TenPayKey, tencentparam.TenPayNotify, tencentparam.TenPayWxOpenNotify); string nonceStr = TenPayV3Util.GetNoncestr(); //string outTradeNo = Order.WXPayBillno; //string outRefundNo = result.RefundNumber; //var totalFee = (int)(ServiceResult.result.item.ServiceExpense * 100);//单位:分 //var totalFee = totalFee;//单位:分 //int refundFee = totalFee; string opUserId = TenPayV3Info.MchId; var notifyUrl = "http://admin/integraltel.com/api/RefundPayNotify"; var dataInfo = new TenPayV3RefundRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, TenPayV3Info.Key, null, nonceStr, null, outTradeNo, outRefundNo, totalFee, refundFee, opUserId, null, refundDescription: msg, notifyUrl: notifyUrl); var cert = @"C:\cert\apiclient_cert.p12"; //根据自己的证书位置修改 var password = TenPayV3Info.MchId; //默认为商户号,建议修改 Thread.Sleep(50); var wxpayresult = await TenPayV3.RefundAsync(dataInfo, cert, password); Thread.Sleep(50); model.code = wxpayresult.result_code; model.msg = wxpayresult.return_msg; } catch (Exception ex) { model.code = "FAIL"; model.msg = ex.Message.ToString(); } return(model); }
public async Task <JsonResult> GetPaySign(PayInput input) { using (CurrentUnitOfWork.DisableFilter(DataFilters.MustHaveTenant, DataFilters.MayHaveTenant)) { Order order = _orderRepository.Get(input.Id); TenPayV3Info tenPayV3Info = await GetTenPayV3Info(InfrastructureSession.TenantId.Value); string timeStamp = TenPayV3Util.GetTimestamp(); string nonceStr = TenPayV3Util.GetNoncestr(); if (order.PrepayIdCreatedTime.HasValue && order.PrepayIdCreatedTime < DateTime.Now.AddHours(-2)) { throw new UserFriendlyException(L("TheOrderHasOverTime")); } if (string.IsNullOrEmpty(order.PrepayId)) { string body = order.Title; //商品或支付单简要描述 string out_trade_no = order.Number; //商户系统内部的订单号,32个字符内,可包含字母,其他说明见商户订单号 int totalFee = (int)(order.PayMoney * 100); //订单总金额,只能是整数。 string spbill_create_ip = Request.UserHostAddress; //APP和网页支付提交用户端IP,Native支付填调用微信支付API的机器IP string openid = WechatUserManager.GetOpenid(order.User.ToUserIdentifier()); TenPayV3UnifiedorderRequestData xmlDataInfo = new TenPayV3UnifiedorderRequestData( tenPayV3Info.AppId, tenPayV3Info.MchId, body, out_trade_no, totalFee, Request.UserHostAddress, tenPayV3Info.TenPayV3Notify, //trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识。必传,这里需要将去获取openid赋值上去 TenPayV3Type.JSAPI, openid, tenPayV3Info.Key, nonceStr); UnifiedorderResult unifiedorderResult = TenPayV3.Unifiedorder(xmlDataInfo, 10000); string prepay_id = unifiedorderResult.prepay_id; order.PrepayId = prepay_id; order.PrepayIdCreatedTime = DateTime.Now; _orderRepository.Update(order); } nonceStr = TenPayV3Util.GetNoncestr(); RequestHandler paysignReqHandler = new RequestHandler(null); paysignReqHandler.Init(); //设置支付参数 paysignReqHandler.SetParameter("appId", tenPayV3Info.AppId); paysignReqHandler.SetParameter("timeStamp", timeStamp); paysignReqHandler.SetParameter("nonceStr", nonceStr); string package = string.Format("prepay_id={0}", order.PrepayId); paysignReqHandler.SetParameter("package", package); string paySign = TenPayV3.GetJsPaySign(tenPayV3Info.AppId, timeStamp, nonceStr, package, tenPayV3Info.Key); paysignReqHandler.SetParameter("paySign", paySign); return(Json(paysignReqHandler.GetAllParameters())); } }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); //提供微信支付信息 var weixinPay_PartnerId = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_PartnerId"]; var weixinPay_Key = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_Key"]; var weixinPay_AppId = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_AppId"]; var weixinPay_AppKey = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_AppKey"]; var weixinPay_TenpayNotify = System.Configuration.ConfigurationManager.AppSettings["WeixinPay_TenpayNotify"]; var tenPayV3_MchId = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_MchId"]; var tenPayV3_Key = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_Key"]; var tenPayV3_AppId = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_AppId"]; var tenPayV3_AppSecret = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_AppSecret"]; var tenPayV3_TenpayNotify = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_TenpayNotify"]; var weixinPayInfo = new TenPayInfo(weixinPay_PartnerId, weixinPay_Key, weixinPay_AppId, weixinPay_AppKey, weixinPay_TenpayNotify); TenPayInfoCollection.Register(weixinPayInfo); var tenPayV3Info = new TenPayV3Info(tenPayV3_AppId, tenPayV3_AppSecret, tenPayV3_MchId, tenPayV3_Key, tenPayV3_TenpayNotify); TenPayV3InfoCollection.Register(tenPayV3Info); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); LogHelper.SetConfig(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); // BundleConfig.RegisterBundles(BundleTable.Bundles); #region 微信公众号相关配置 var appId = ConfigurationManager.AppSettings["WeixinAppId"]; var secret = ConfigurationManager.AppSettings["WeixinAppSecret"]; AccessTokenContainer.Register(appId, secret); var tenPayV3_MchId = ConfigurationManager.AppSettings["TenPayV3_MchId"]; var tenPayV3_Key = ConfigurationManager.AppSettings["TenPayV3_Key"]; var tenPayV3_AppId = ConfigurationManager.AppSettings["TenPayV3_AppId"]; var tenPayV3_AppSecret = ConfigurationManager.AppSettings["TenPayV3_AppSecret"]; var tenPayV3_TenpayNotify = ConfigurationManager.AppSettings["TenPayV3_TenpayNotify"]; var tenPayV3Info = new TenPayV3Info(tenPayV3_AppId, tenPayV3_AppSecret, tenPayV3_MchId, tenPayV3_Key, tenPayV3_TenpayNotify); TenPayV3InfoCollection.Register(tenPayV3Info); #endregion RegisterView(); //注册视图访问规则 MyJobScheduler.Run(); }
/// <summary> /// 注册微信支付 /// </summary> private void RegisterWeixinPay() { var senparcWeixinSetting = Senparc.Weixin.Config.DefaultSenparcWeixinSetting; //提供微信支付信息 var weixinPay_PartnerId = senparcWeixinSetting.WeixinPay_PartnerId; var weixinPay_Key = senparcWeixinSetting.WeixinPay_Key; var weixinPay_AppId = senparcWeixinSetting.WeixinPay_AppId; var weixinPay_AppKey = senparcWeixinSetting.WeixinPay_AppKey; var weixinPay_TenpayNotify = senparcWeixinSetting.WeixinPay_TenpayNotify; var tenPayV3_MchId = senparcWeixinSetting.TenPayV3_MchId; var tenPayV3_Key = senparcWeixinSetting.TenPayV3_Key; var tenPayV3_AppId = senparcWeixinSetting.TenPayV3_AppId; var tenPayV3_AppSecret = senparcWeixinSetting.TenPayV3_AppSecret; var tenPayV3_TenpayNotify = senparcWeixinSetting.TenPayV3_TenpayNotify; var weixinPayInfo = new TenPayInfo(weixinPay_PartnerId, weixinPay_Key, weixinPay_AppId, weixinPay_AppKey, weixinPay_TenpayNotify); TenPayInfoCollection.Register(weixinPayInfo);//微信V2(旧版) var tenPayV3Info = new TenPayV3Info(tenPayV3_AppId, tenPayV3_AppSecret, tenPayV3_MchId, tenPayV3_Key, tenPayV3_TenpayNotify); TenPayV3InfoCollection.Register(tenPayV3Info);//微信V3(新版) }
public async Task <TenPayV3Info> GetTenPayV3Info(int tenantId) { TenPayV3Info tenPayV3Info = await WechatCommonManager.GetTenPayV3InfoAsync( tenantId, Url.Action("PayNotify", "Pay", null, Request.Url.Scheme)); return(tenPayV3Info); }
public async Task <TenPayV3Info> GetTenPayV3Info() { if (_tenPayV3Info == null) { _tenPayV3Info = await WechatCommonManager.GetTenPayV3InfoAsync(InfrastructureSession.TenantId.Value, null); } return(_tenPayV3Info); }
public PaymentCallBackBuss() { tenPayV3Info = new TenPayV3Info( Global.APPID, Global.APPSECRET, Global.MCHID, Global.PaymentKey, Global.CallBackUrl); }
/// <summary> /// 患者微信支付下订单 /// </summary> /// <returns></returns> public async Task <TencentJSPayRequestModel> UnifiedorderAsync(bool sharing, string spbillCreateIp, YaeherConsultation consul, YaeherUser user, ServiceMoneyList product, SystemConfigs tencentparam) { TencentJSPayRequestModel jspay = new TencentJSPayRequestModel(); try { TenPayV3Info tenPayV3Info = new TenPayV3Info(tencentparam.AppID, tencentparam.AppSecret, tencentparam.TenPayMchId, tencentparam.TenPayKey, tencentparam.TenPayNotify, tencentparam.TenPayWxOpenNotify); //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一 // var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss"); // var sjs =;//随机数 var sjs = consul.ConsultNumber.Substring(3, consul.ConsultNumber.Length - 3) + TenPayV3Util.BuildRandomStr(6); var sp_billno = sjs; // var sp_billno = string.Format("{0}{1}", sjs, user.Id); var shortbillno = sp_billno; TenPayInfo tenPayInfo = new TenPayInfo(); // var body = product == null ? "怡芽问诊" : product.DoctorName+"医生" + product.ServiceType; var body = "怡禾健康咨询"; var price = product == null ? 100 : (int)(product.ServiceExpense * 100);//单位:分 var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var xmlDataInfo = new TenPayV3UnifiedorderRequestData(tenPayV3Info.AppId, tenPayV3Info.MchId, body, sp_billno, price, spbillCreateIp, tenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, user.WecharOpenID, tenPayV3Info.Key, nonceStr); //CreateWrite("C:\\回调.txt", "订单参数:" + JsonHelper.ToJson(xmlDataInfo)); var result = await UnifiedorderAsync(xmlDataInfo, sharing? "Y" : "N"); //调用统一订单接口 //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,); if (result.IsResultCodeSuccess()) { var package = string.Format("prepay_id={0}", result.prepay_id); var paysign = TenPayV3.GetJsPaySign(tenPayV3Info.AppId, timeStamp, nonceStr, package, tenPayV3Info.Key); jspay.product = product; jspay.timeStamp = timeStamp; jspay.nonceStr = nonceStr; jspay.package = package; jspay.paySign = paysign; jspay.appid = tenPayV3Info.AppId; jspay.sp_billno = shortbillno; jspay.code = result.result_code; jspay.msg = result.return_msg; } else { jspay.code = result.result_code; jspay.msg = result.return_msg; } } catch (Exception ex) { jspay.code = "FAIL"; jspay.msg = ex.Message.ToString(); } return(jspay); }
/// <summary> /// 退款申请接口 /// </summary> /// <returns></returns> public async Task <ActionResult> Refund() { string nonceStr = TenPayV3Util.GetNoncestr(); RequestHandler packageReqHandler = new RequestHandler(null); TenPayV3Info TenPayV3Info = await GetTenPayV3Info(InfrastructureSession.TenantId.Value); //设置package订单参数 packageReqHandler.SetParameter("appid", TenPayV3Info.AppId); //公众账号ID packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId); //商户号 packageReqHandler.SetParameter("out_trade_no", ""); //填入商家订单号 packageReqHandler.SetParameter("out_refund_no", ""); //填入退款订单号 packageReqHandler.SetParameter("total_fee", ""); //填入总金额 packageReqHandler.SetParameter("refund_fee", ""); //填入退款金额 packageReqHandler.SetParameter("op_user_id", TenPayV3Info.MchId); //操作员Id,默认就是商户号 packageReqHandler.SetParameter("nonce_str", nonceStr); //随机字符串 string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key); packageReqHandler.SetParameter("sign", sign); //签名 //退款需要post的数据 string data = packageReqHandler.ParseXML(); //退款接口地址 string url = "https://api.mch.weixin.qq.com/secapi/pay/refund"; //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中) string cert = @"F:\apiclient_cert.p12"; //私钥(在安装证书时设置) string password = ""; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); //调用证书 X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet); #region 发起post请求 HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url); webrequest.ClientCertificates.Add(cer); webrequest.Method = "post"; byte[] postdatabyte = Encoding.UTF8.GetBytes(data); webrequest.ContentLength = postdatabyte.Length; Stream stream; stream = webrequest.GetRequestStream(); stream.Write(postdatabyte, 0, postdatabyte.Length); stream.Close(); HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse(); StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()); string responseContent = streamReader.ReadToEnd(); #endregion var res = XDocument.Parse(responseContent); string openid = res.Element("xml").Element("out_refund_no").Value; return(Content(openid)); }
public async Task <OrderQueryResult> OrderQueryAsync(string WXPayBillno, SystemConfigs tencentparam) { TenPayV3Info TenPayV3Info = new TenPayV3Info(tencentparam.AppID, tencentparam.AppSecret, tencentparam.TenPayMchId, tencentparam.TenPayKey, tencentparam.TenPayNotify, tencentparam.TenPayWxOpenNotify); string nonceStr = TenPayV3Util.GetNoncestr(); TenPayV3OrderQueryRequestData querydata = new TenPayV3OrderQueryRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, "", nonceStr, WXPayBillno, TenPayV3Info.Key); var tencentpayresult = await TenPayV3.OrderQueryAsync(querydata); return(tencentpayresult); }
public async Task <TenPayV3Info> GetTenPayV3InfoAsync(int tenantId, string tenPayV3Notify) { string appId = await SettingManager.GetSettingValueForTenantAsync(WechatSettings.General.AppId, tenantId); string appSecret = await SettingManager.GetSettingValueForTenantAsync(WechatSettings.General.Secret, tenantId); string mchId = await SettingManager.GetSettingValueForTenantAsync(WechatSettings.Pay.MchId, tenantId); string key = await SettingManager.GetSettingValueForTenantAsync(WechatSettings.Pay.Key, tenantId); TenPayV3Info tenPayV3Info = new TenPayV3Info(appId, appSecret, mchId, key, tenPayV3Notify); return(tenPayV3Info); }
/// <summary> /// 注册微信支付 /// </summary> private void RegisterWeixinPay() { //提供微信支付信息 var tenPayV3_MchId = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_MchId"]; var tenPayV3_Key = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_Key"]; var tenPayV3_AppId = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_AppId"]; var tenPayV3_AppSecret = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_AppSecret"]; var tenPayV3_TenpayNotify = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_TenpayNotify"]; var tenPayV3Info = new TenPayV3Info(tenPayV3_AppId, tenPayV3_AppSecret, tenPayV3_MchId, tenPayV3_Key, tenPayV3_TenpayNotify); TenPayV3InfoCollection.Register(tenPayV3Info); }
static TenPayV3Info GetTenPayInfo() { var tenPayV3_MchId = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_MchId"]; var tenPayV3_Key = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_Key"]; var tenPayV3_AppId = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_AppId"]; var tenPayV3_AppSecret = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_AppSecret"]; //var tenPayV3_TenpayNotify = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_TenpayNotify"]; //var weixinPayInfo = new TenPayInfo(weixinPay_PartnerId, weixinPay_Key, weixinPay_AppId, weixinPay_AppKey, weixinPay_TenpayNotify); //TenPayInfoCollection.Register(weixinPayInfo); var tenPayV3Info = new TenPayV3Info(tenPayV3_AppId, tenPayV3_AppSecret, tenPayV3_MchId, tenPayV3_Key, ""); return(tenPayV3Info); }
public async Task Refund(Order order, long refundFee) { TenPayV3Info TenPayV3Info = await GetTenPayV3Info(); string nonceStr = TenPayV3Util.GetNoncestr(); RequestHandler packageReqHandler = new RequestHandler(null); //设置package订单参数 packageReqHandler.SetParameter("appid", TenPayV3Info.AppId); //公众账号ID packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId); //商户号 packageReqHandler.SetParameter("out_trade_no", order.Number); //填入商家订单号 packageReqHandler.SetParameter("out_refund_no", NumberProvider.BuildNumber()); //填入退款订单号 packageReqHandler.SetParameter("total_fee", (order.PayMoney * 100).ToString()); //填入总金额 packageReqHandler.SetParameter("refund_fee", (refundFee * 100).ToString()); //填入退款金额 packageReqHandler.SetParameter("op_user_id", TenPayV3Info.MchId); //操作员Id,默认就是商户号 packageReqHandler.SetParameter("nonce_str", nonceStr); //随机字符串 string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key); packageReqHandler.SetParameter("sign", sign); //签名 //退款需要post的数据 string data = packageReqHandler.ParseXML(); //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中) string cert = @"F:\apiclient_cert.p12"; //私钥(在安装证书时设置) string password = ""; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); //调用证书 X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet); #region 发起post请求 HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(RefundUrl); webrequest.ClientCertificates.Add(cer); webrequest.Method = "post"; byte[] postdatabyte = Encoding.UTF8.GetBytes(data); webrequest.ContentLength = postdatabyte.Length; Stream stream; stream = webrequest.GetRequestStream(); stream.Write(postdatabyte, 0, postdatabyte.Length); stream.Close(); HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse(); StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()); string responseContent = streamReader.ReadToEnd(); #endregion }
public async Task <ContentResult> PayNotify() { ResponseHandler responseHandler = new ResponseHandler(null); string return_code = responseHandler.GetParameter("return_code"); string return_msg = responseHandler.GetParameter("return_msg"); string openid = responseHandler.GetParameter("openid"); using (CurrentUnitOfWork.DisableFilter(DataFilters.MayHaveTenant)) { UserLogin userLogin = _userLoginRepository.GetAll().Where(model => model.ProviderKey == openid).FirstOrDefault(); TenPayV3Info tenPayV3Info = await GetTenPayV3Info(userLogin.TenantId.Value); responseHandler.SetKey(tenPayV3Info.Key); } //验证请求是否从微信发过来(安全) if (responseHandler.IsTenpaySign()) { if (return_code == "SUCCESS") { string result_code = responseHandler.GetParameter("result_code"); if (result_code == "SUCCESS") { string out_trade_no = responseHandler.GetParameter("out_trade_no"); using (CurrentUnitOfWork.DisableFilter(DataFilters.MustHaveTenant, DataFilters.MayHaveTenant)) { Order order = _orderRepository.GetAll().Where(model => model.Number == out_trade_no).FirstOrDefault(); if (order.PaymentStatus == PaymentStatus.ToPay) { await OrderManager.PayCallback(order, PayType.WeChat); } } } } } string xml = string.Format( @"<xml><return_code><![CDATA[{0}]]></return_code><return_msg><![CDATA[{1}]]></return_msg></xml>", return_code, return_msg); return(Content(xml, "text/xml")); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); #region 初始化数据访问对象 Libraries.Core.ServiceLocator.Initialization(); #endregion var mchId = System.Configuration.ConfigurationManager.AppSettings["mchId"]; var appId = System.Configuration.ConfigurationManager.AppSettings["appid"]; var appSecret = System.Configuration.ConfigurationManager.AppSettings["appSecret"]; var apiKey = System.Configuration.ConfigurationManager.AppSettings["apiKey"]; var notifyUrl = System.Configuration.ConfigurationManager.AppSettings["notifyUrl"]; var tenPayV3Info = new TenPayV3Info(appId, appSecret, mchId, apiKey, notifyUrl); TenPayV3InfoCollection.Register(tenPayV3Info); }
/// <summary> /// 注册微信支付 /// </summary> private void RegisterWeixinPay() { //提供微信支付信息 var weixinPay_PartnerId = ConfigurationManager.AppSettings["WeixinPay_PartnerId"]; var weixinPay_Key = ConfigurationManager.AppSettings["WeixinPay_Key"]; var weixinPay_AppId = ConfigurationManager.AppSettings["WeixinPay_AppId"]; var weixinPay_AppKey = ConfigurationManager.AppSettings["WeixinPay_AppKey"]; var weixinPay_TenpayNotify = ConfigurationManager.AppSettings["WeixinPay_TenpayNotify"]; var tenPayV3_MchId = ConfigurationManager.AppSettings["TenPayV3_MchId"]; var tenPayV3_Key = ConfigurationManager.AppSettings["TenPayV3_Key"]; var tenPayV3_AppId = ConfigurationManager.AppSettings["TenPayV3_AppId"]; var tenPayV3_AppSecret = ConfigurationManager.AppSettings["TenPayV3_AppSecret"]; var tenPayV3_TenpayNotify = ConfigurationManager.AppSettings["TenPayV3_TenpayNotify"]; var weixinPayInfo = new TenPayInfo(weixinPay_PartnerId, weixinPay_Key, weixinPay_AppId, weixinPay_AppKey, weixinPay_TenpayNotify); TenPayInfoCollection.Register(weixinPayInfo); var tenPayV3Info = new TenPayV3Info(tenPayV3_AppId, tenPayV3_AppSecret, tenPayV3_MchId, tenPayV3_Key, tenPayV3_TenpayNotify); TenPayV3InfoCollection.Register(tenPayV3Info); }
/// <summary> /// 订单退款 /// </summary> /// <param name="billNo">订单号</param> /// <param name="billFee">退款金额(单位:分)</param> /// <param name="tenPayV3Notif">回调地址</param> /// <returns></returns> public static string Refund(string billNo, int billFee, string tenPayV3Notif) { try { TenPayV3Info tenPayV3Info = new TenPayV3Info(WxOpenId, WxOpenSecret, MchId, MchIdkey, tenPayV3Notif); string nonceStr = TenPayV3Util.GetNoncestr(); string outTradeNo = billNo; string outRefundNo = "OutRefunNo-" + DateTime.Now.Ticks; int totalFee = billFee; int refundFee = totalFee; string opUserId = tenPayV3Info.MchId; var dataInfo = new TenPayV3RefundRequestData( tenPayV3Info.AppId, tenPayV3Info.MchId, tenPayV3Info.Key, null, //描述 nonceStr, null, //微信订单号 outTradeNo, //商户订单号 二选一 outRefundNo, //商户退款单号 totalFee, //订单金额 refundFee, //退款金额 opUserId, null //退款资金来源 ); var cert = CertPath; //根据自己的证书位置修改 var password = CertPassword; //默认为商户号,建议修改 var result = TenPayV3.Refund(dataInfo, cert, password); Log.WriteLogToTxt("订单退款 result:" + JsonHelper.ToJson(result), LogType.Info); return(result.result_code == "FAIL" ? result.err_code_des : "成功"); } catch (Exception ex) { WxWriteLogError(ex, "异常退款"); } return(""); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var _appId = System.Web.Configuration.WebConfigurationManager.AppSettings["WeixinAppId"]; var _appSecret = System.Web.Configuration.WebConfigurationManager.AppSettings["WeixinAppSecret"]; var tenPayV3_MchId = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_MchId"]; var tenPayV3_Key = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_Key"]; var tenPayV3_AppId = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_AppId"]; var tenPayV3_AppSecret = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_AppSecret"]; var tenPayV3_TenpayNotify = System.Configuration.ConfigurationManager.AppSettings["TenPayV3_TenpayNotify"]; var tenPayV3Info = new TenPayV3Info(tenPayV3_AppId, tenPayV3_AppSecret, tenPayV3_MchId, tenPayV3_Key, tenPayV3_TenpayNotify); TenPayV3InfoCollection.Register(tenPayV3Info); Senparc.Weixin.MP.Containers.AccessTokenContainer.Register(_appId, _appSecret); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions <SenparcSetting> senparcSetting, IOptions <SenparcWeixinSetting> senparcWeixinSetting) { //引入EnableRequestRewind中间件 app.UseEnableRequestRewind(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); #region 提供网站根目录(当前 Sample 用到,和 SDK 无关) if (env.ContentRootPath != null) { Senparc.Weixin.MP.Sample.CommonService.Utilities.Server.AppDomainAppPath = env.ContentRootPath; // env.ContentRootPath; } Senparc.Weixin.MP.Sample.CommonService.Utilities.Server.WebRootPath = env.WebRootPath; // env.ContentRootPath; #endregion // 启动 CO2NET 全局注册,必须! IRegisterService register = RegisterService.Start(env, senparcSetting.Value) .UseSenparcGlobal(false, () => GetExCacheStrategies(senparcSetting.Value)); //如果需要自动扫描自定义扩展缓存,可以这样使用: //register.UseSenparcWeixin(true); //如果需要指定自定义扩展缓存,可以这样用: //register.UseSenparcWeixin(false, GetExCacheStrategies); #region CO2NET 全局配置 #region 注册线程,在 RegisterService.Start() 中已经自动注册,此处也可以省略,仅作演示 register.RegisterThreads(); //启动线程,RegisterThreads()也可以省略,在RegisterService.Start()中已经自动注册 #endregion #region 缓存配置(按需) // 当同一个分布式缓存同时服务于多个网站(应用程序池)时,可以使用命名空间将其隔离(非必须) register.ChangeDefaultCacheNamespace("DefaultCO2NETCache"); //配置全局使用Redis缓存(按需,独立) var redisConfigurationStr = senparcSetting.Value.Cache_Redis_Configuration; var useRedis = !string.IsNullOrEmpty(redisConfigurationStr) && redisConfigurationStr != "Redis配置"; if (useRedis)//这里为了方便不同环境的开发者进行配置,做成了判断的方式,实际开发环境一般是确定的 { //设置Redis链接信息,并在全局立即启用Redis缓存。 register.RegisterCacheRedis(redisConfigurationStr, redisConfiguration => RedisObjectCacheStrategy.Instance); //此外还可以通过这种方式修改 Redis 链接信息(不立即启用): //RedisManager.ConfigurationOption = redisConfigurationStr; //以下会立即将全局缓存设置为Redis(不修改配置)。 //如果要使用其他缓存,同样可以在任意地方使用这个方法,修改 RedisObjectCacheStrategy 为其他缓存策略 //CacheStrategyFactory.RegisterObjectCacheStrategy(() => RedisObjectCacheStrategy.Instance); } //如果这里不进行Redis缓存启用,则目前还是默认使用内存缓存 //配置Memcached缓存(按需,独立) //这里配置的是 CO2NET 的 Memcached 缓存(如果执行了下面的 app.UseSenparcWeixinCacheMemcached(), //会自动包含本步骤,这一步注册可以忽略) var useMemcached = false; app.UseWhen(h => useMemcached, a => { a.UseEnyimMemcached(); //确保Memcached连接可用后,启用下面的做法 //var memcachedConnStr = senparcSetting.Value.Cache_Memcached_Configuration; //var memcachedConnDic = new Dictionary<string, int>() {/*进行配置 { "localhost", 9101 }*/ };//可以由 memcachedConnStr 分割得到,或直接填写 //register.RegisterCacheMemcached(memcachedConnDic, memcachedConfig => MemcachedObjectCacheStrategy.Instance); }); #endregion #region 注册日志(按需,建议) register.RegisterTraceLog(ConfigTraceLog);//配置TraceLog #endregion #endregion #region 微信相关配置 /* 微信配置开始 * * 建议按照以下顺序进行注册,尤其须将缓存放在第一位! */ //注册开始 #region 微信缓存(按需,必须在 register.UseSenparcWeixin() 之前) // 微信的 Memcached 缓存,如果不使用则注释掉(开启前必须保证配置有效,否则会抛错) if (useMemcached) { app.UseSenparcWeixinCacheMemcached(); } //app.UseWhen(h => useMemcached, a => a.UseSenparcWeixinCacheMemcached());//如果连接而配置未生效,不能这么使用 //微信的 Redis 缓存,如果不使用则注释掉(开启前必须保证配置有效,否则会抛错) if (useRedis) { app.UseSenparcWeixinCacheRedis(); } //app.UseWhen(h => useRedis, a => a.UseSenparcWeixinCacheRedis());//如果连接而配置未生效,不能这么使用 #endregion //开始注册微信信息,必须! register.UseSenparcWeixin(senparcWeixinSetting.Value, senparcSetting.Value) //注意:上一行没有 ; 下面可接着写 .RegisterXX() #region 注册公众号或小程序(按需) //注册公众号 .RegisterMpAccount( senparcWeixinSetting.Value.WeixinAppId, senparcWeixinSetting.Value.WeixinAppSecret, "【盛派网络小助手】公众号") //注册多个公众号或小程序 .RegisterMpAccount( senparcWeixinSetting.Value.WxOpenAppId, senparcWeixinSetting.Value.WxOpenAppSecret, "【盛派网络小助手】小程序") //注意:小程序和公众号的AppId/Secret属于并列关系,这里name需要区分开 #endregion #region 注册企业号(按需) //注册企业号 .RegisterWorkAccount( senparcWeixinSetting.Value.WeixinCorpId, senparcWeixinSetting.Value.WeixinCorpSecret, "【盛派网络】企业微信") //还可注册任意多个企业号 #endregion #region 注册微信支付(按需) //注册旧微信支付版本(V2) .RegisterTenpayOld(() => { //提供微信支付(旧版本)信息 var weixinPayInfo = new TenPayInfo(senparcWeixinSetting.Value); return(weixinPayInfo); }, "【盛派网络小助手】公众号"//这里的 name 和第一个 RegisterMpAccount() 中的一致,会被记录到同一个 SenparcWeixinSettingItem 对象中 ) //注册最新微信支付版本(V3) .RegisterTenpayV3(() => { //提供微信支付(新版本 V3)信息 var tenPayV3Info = new TenPayV3Info(senparcWeixinSetting.Value); return(tenPayV3Info); }, "【盛派网络小助手】公众号") //记录到同一个 SenparcWeixinSettingItem 对象中 #endregion #region 注册微信第三方平台(按需) .RegisterOpenComponent( senparcWeixinSetting.Value.Component_Appid, senparcWeixinSetting.Value.Component_Secret, //getComponentVerifyTicketFunc componentAppId => { var dir = Path.Combine(Server.GetMapPath("~/App_Data/OpenTicket")); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var file = Path.Combine(dir, string.Format("{0}.txt", componentAppId)); using (var fs = new FileStream(file, FileMode.Open)) { using (var sr = new StreamReader(fs)) { var ticket = sr.ReadToEnd(); return(ticket); } } }, //getAuthorizerRefreshTokenFunc (componentAppId, auhtorizerId) => { var dir = Path.Combine(Server.GetMapPath("~/App_Data/AuthorizerInfo/" + componentAppId)); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId)); if (!File.Exists(file)) { return(null); } using (Stream fs = new FileStream(file, FileMode.Open)) { var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); var result = (RefreshAuthorizerTokenResult)binFormat.Deserialize(fs); return(result.authorizer_refresh_token); } }, //authorizerTokenRefreshedFunc (componentAppId, auhtorizerId, refreshResult) => { var dir = Path.Combine(Server.GetMapPath("~/App_Data/AuthorizerInfo/" + componentAppId)); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId)); using (Stream fs = new FileStream(file, FileMode.Create)) { //这里存了整个对象,实际上只存RefreshToken也可以,有了RefreshToken就能刷新到最新的AccessToken var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); binFormat.Serialize(fs, refreshResult); fs.Flush(); } }, "【盛派网络】开放平台") #endregion ; /* 微信配置结束 */ #endregion }
public AppWeChatPayService() { _tenPayV3Info = new TenPayV3Info(AppId, AppSecret, MchId, Key, ServerPath + TenPayV3Notify); Logger = NullLogger.Instance; }
public async Task <ApiResult <WeixinJsPaySignature> > Pay([FromBody] PayModelInput model, CancellationToken cancelToken) { /* * 接口根据订单id和小程序Code * 获取支付调起参数 */ if (string.IsNullOrWhiteSpace(model.Id)) { throw new NotImplementedException("订单Id信息为空!"); } //查询订单 var data = await _orderRepository.GetIncludeAsync(model.Id, cancelToken); ApiResult <WeixinJsPaySignature> apiResult = new ApiResult <WeixinJsPaySignature>(); _ = new ApiResult(); string timeStamp = TenPayV3Util.GetTimestamp(); AppLogger.Debug(JsonConvert.SerializeObject("1" + timeStamp), JsonConvert.SerializeObject(timeStamp)); string nonceStr = TenPayV3Util.GetNoncestr(); AppLogger.Debug(JsonConvert.SerializeObject("2" + nonceStr), JsonConvert.SerializeObject(nonceStr)); string PayV3_TenpayNotify = ConfigurationManager.AppSettings["PayV3_TenpayNotify"]; TenPayV3Info tenPayV3Info = new TenPayV3Info(GuoGuoCommunity_WxOpenAppId, GuoGuoCommunity_WxOpenAppSecret, PayV3_MchId, PayV3_Key, string.Empty, string.Empty, PayV3_TenpayNotify, string.Empty); AppLogger.Debug(JsonConvert.SerializeObject(tenPayV3Info), JsonConvert.SerializeObject(tenPayV3Info)); var openIdResult = SnsApi.JsCode2Json(GuoGuoCommunity_WxOpenAppId, GuoGuoCommunity_WxOpenAppSecret, model.Code); AppLogger.Debug(JsonConvert.SerializeObject(openIdResult), JsonConvert.SerializeObject(openIdResult)); var xmlDataInfo = new TenPayV3UnifiedorderRequestData(tenPayV3Info.AppId, tenPayV3Info.MchId, "呙呙社区购物", data.Number, Convert.ToInt32(data.PaymentPrice * 100), GetClientIpAddress(Request), tenPayV3Info.TenPayV3Notify, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, openIdResult.openid, tenPayV3Info.Key, nonceStr, attach: data.Id.ToString()); AppLogger.Debug(DateTime.Now.ToString("yyyyMMddHHmmss") + "****TenPayV3UnifiedorderRequestData对象" + JsonConvert.SerializeObject(xmlDataInfo), "****TenPayV3UnifiedorderRequestData对象" + JsonConvert.SerializeObject(xmlDataInfo)); var resultPay = await TenPayV3.UnifiedorderAsync(xmlDataInfo); AppLogger.Debug("****TenPayV3.Unifiedorder返回对象" + JsonConvert.SerializeObject(resultPay), "****TenPayV3.Unifiedorder返回对象" + JsonConvert.SerializeObject(resultPay)); if (resultPay.return_code.ToUpper() == "SUCCESS") { if (resultPay.result_code.ToUpper() == "SUCCESS") { //设置支付参数 RequestHandler paySignReqHandler = new RequestHandler(null); paySignReqHandler.SetParameter("appId", tenPayV3Info.AppId); paySignReqHandler.SetParameter("timeStamp", timeStamp); paySignReqHandler.SetParameter("nonceStr", nonceStr); paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", resultPay.prepay_id)); paySignReqHandler.SetParameter("signType", "MD5"); paySignReqHandler.SetParameter("nonceStr", nonceStr); string paySign = paySignReqHandler.CreateMd5Sign("key", tenPayV3Info.Key); var jsmodel = new WeixinJsPaySignature { AppId = tenPayV3Info.AppId, Timestamp = timeStamp, NonceStr = nonceStr, Package = string.Format("prepay_id={0}", resultPay.prepay_id), PaySign = paySign, OrderId = data.Number, SignType = "MD5" }; apiResult.Data = jsmodel; return(apiResult); } else { } } else { throw new NotImplementedException(JsonConvert.SerializeObject(resultPay)); } return(apiResult); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions <SenparcWeixinSetting> senparcWeixinSetting) { //引入EnableRequestRewind中间件 app.UseEnableRequestRewind(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); #region 微信相关配置 #region 提供网站根目录(当前 Sample 用到,和 SDK 无关) if (env.ContentRootPath != null) { Senparc.Weixin.MP.Sample.CommonService.Utilities.Server.AppDomainAppPath = env.ContentRootPath; // env.ContentRootPath; } Senparc.Weixin.MP.Sample.CommonService.Utilities.Server.WebRootPath = env.WebRootPath; // env.ContentRootPath; #endregion /* 微信配置开始 * * 建议按照以下顺序进行注册,尤其须将缓存放在第一位! */ //注册开始 var isDebug = true; //当前是否是Debug状态 RegisterService.Start(env, senparcWeixinSetting, isDebug) //这里没有 ; 下面接着写 #region 缓存配置 // 当同一个分布式缓存同时服务于多个网站(应用程序池)时,可以使用命名空间将其隔离(非必须) .ChangeDefaultCacheNamespace("DefaultWeixinCache") //配置Redis缓存 .RegisterCacheRedis( senparcWeixinSetting.Value.Cache_Redis_Configuration, redisConfiguration => (!string.IsNullOrEmpty(redisConfiguration) && redisConfiguration != "Redis配置") ? RedisObjectCacheStrategy.Instance : null) #endregion #region 注册日志(按需) .RegisterTraceLog(ConfigWeixinTraceLog) //配置TraceLog #endregion #region 注册线程(必须) 在Start()中已经自动注册,此处也可以省略,仅作演示 .RegisterThreads() //启动线程,RegisterThreads()也可以省略,在Start()中已经自动注册 #endregion #region 注册公众号或小程序(按需) //注册公众号 .RegisterMpAccount( senparcWeixinSetting.Value.WeixinAppId, senparcWeixinSetting.Value.WeixinAppSecret, "【盛派网络小助手】公众号") //注册多个公众号或小程序 .RegisterMpAccount( senparcWeixinSetting.Value.WxOpenAppId, senparcWeixinSetting.Value.WxOpenAppSecret, "【盛派互动】小程序") #endregion #region 注册企业号(按需) //注册企业号 .RegisterWorkAccount( senparcWeixinSetting.Value.WeixinCorpId, senparcWeixinSetting.Value.WeixinCorpSecret, "【盛派网络】企业微信") //还可注册任意多个企业号 #endregion #region 注册微信支付(按需) //注册旧微信支付版本(V2) .RegisterTenpayOld(() => { //提供微信支付信息 var weixinPay_PartnerId = senparcWeixinSetting.Value.WeixinPay_PartnerId; var weixinPay_Key = senparcWeixinSetting.Value.WeixinPay_Key; var weixinPay_AppId = senparcWeixinSetting.Value.WeixinPay_AppId; var weixinPay_AppKey = senparcWeixinSetting.Value.WeixinPay_AppKey; var weixinPay_TenpayNotify = senparcWeixinSetting.Value.WeixinPay_TenpayNotify; var weixinPayInfo = new TenPayInfo(weixinPay_PartnerId, weixinPay_Key, weixinPay_AppId, weixinPay_AppKey, weixinPay_TenpayNotify); return(weixinPayInfo); }) //注册最新微信支付版本(V3) .RegisterTenpayV3(() => { //提供微信支付信息 var tenPayV3_MchId = senparcWeixinSetting.Value.TenPayV3_MchId; var tenPayV3_Key = senparcWeixinSetting.Value.TenPayV3_Key; var tenPayV3_AppId = senparcWeixinSetting.Value.TenPayV3_AppId; var tenPayV3_AppSecret = senparcWeixinSetting.Value.TenPayV3_AppSecret; var tenPayV3_TenpayNotify = senparcWeixinSetting.Value.TenPayV3_TenpayNotify; var tenPayV3Info = new TenPayV3Info(tenPayV3_AppId, tenPayV3_AppSecret, tenPayV3_MchId, tenPayV3_Key, tenPayV3_TenpayNotify); return(tenPayV3Info); }) #endregion #region 注册微信第三方平台(按需) .RegisterOpenComponent( senparcWeixinSetting.Value.Component_Appid, senparcWeixinSetting.Value.Component_Secret, //getComponentVerifyTicketFunc componentAppId => { var dir = Path.Combine(Server.GetMapPath("~/App_Data/OpenTicket")); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var file = Path.Combine(dir, string.Format("{0}.txt", componentAppId)); using (var fs = new FileStream(file, FileMode.Open)) { using (var sr = new StreamReader(fs)) { var ticket = sr.ReadToEnd(); return(ticket); } } }, //getAuthorizerRefreshTokenFunc (componentAppId, auhtorizerId) => { var dir = Path.Combine(Server.GetMapPath("~/App_Data/AuthorizerInfo/" + componentAppId)); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId)); if (!File.Exists(file)) { return(null); } using (Stream fs = new FileStream(file, FileMode.Open)) { var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); var result = (RefreshAuthorizerTokenResult)binFormat.Deserialize(fs); return(result.authorizer_refresh_token); } }, //authorizerTokenRefreshedFunc (componentAppId, auhtorizerId, refreshResult) => { var dir = Path.Combine(Server.GetMapPath("~/App_Data/AuthorizerInfo/" + componentAppId)); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId)); using (Stream fs = new FileStream(file, FileMode.Create)) { //这里存了整个对象,实际上只存RefreshToken也可以,有了RefreshToken就能刷新到最新的AccessToken var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); binFormat.Serialize(fs, refreshResult); fs.Flush(); } }, "【盛派网络】开放平台"); #endregion ; //配置Memcached缓存 #region Senparc.Weixin SDK Memcached 配置 app.UseEnyimMemcached(); #endregion /* 微信配置结束 */ #endregion }
/// <summary> /// 注册微信支付 /// </summary> public static void RegisterWeixinPay() { var tenPayV3Info = new TenPayV3Info(Instance.AppId, Instance.AppSecret, Instance.MchId, Instance.Key, Instance.Notify); TenPayV3InfoCollection.Register(tenPayV3Info); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions <SenparcWeixinSetting> senparcWeixinSetting) { //引入EnableRequestRewind中间件 app.UseEnableRequestRewind(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); #region 提供网站根目录(当前 Sample 用到,和 SDK 无关) if (env.ContentRootPath != null) { Senparc.Weixin.MP.Sample.CommonService.Utilities.Server.AppDomainAppPath = env.ContentRootPath; // env.ContentRootPath; } Senparc.Weixin.MP.Sample.CommonService.Utilities.Server.WebRootPath = env.WebRootPath; // env.ContentRootPath; #endregion var isDebug = true;//当前是否是Debug状态 IRegisterService register = RegisterService.Start(env, isDebug); #region 注册线程(必须) 在Start()中已经自动注册,此处也可以省略,仅作演示 register.RegisterThreads(); //启动线程,RegisterThreads()也可以省略,在RegisterService.Start()中已经自动注册 #endregion #region 缓存配置(按需) // 当同一个分布式缓存同时服务于多个网站(应用程序池)时,可以使用命名空间将其隔离(非必须) register.ChangeDefaultCacheNamespace("DefaultWeixinCache"); //配置Redis缓存(按需,独立) var redisConfigurationStr = senparcWeixinSetting.Value.Cache_Redis_Configuration; var useRedis = !string.IsNullOrEmpty(redisConfigurationStr) && redisConfigurationStr != "Redis配置"; if (useRedis)//这里为了方便不同环境的开发者进行配置,做成了判断的方式,实际开发环境一般是确定的 { CacheStrategyFactory.RegisterObjectCacheStrategy(() => RedisObjectCacheStrategy.Instance); //如果不进行任何设置,则默认使用内存缓存 } //配置Memcached缓存(按需,独立) //这里配置的是 CO2NET 的 Memcached 缓存(如果执行了下面的 app.UseSenparcWeixinCacheMemcached(), //会自动包含本步骤,这一步注册可以忽略) var useMemcached = false; app.UseWhen(h => useMemcached, a => a.UseEnyimMemcached()); #endregion #region 注册日志(按需) register.RegisterTraceLog(ConfigTraceLog);//配置TraceLog #endregion #region 微信相关配置 /* 微信配置开始 * * 建议按照以下顺序进行注册,尤其须将缓存放在第一位! */ //注册开始 #region 微信缓存(按需,必须在 register.UseSenparcWeixin() 之前) // 微信的 Memcached 缓存,如果不使用则注释掉(开启前必须保证配置有效,否则会抛错) if (useMemcached) { app.UseSenparcWeixinCacheMemcached(); } //app.UseWhen(h => useMemcached, a => a.UseSenparcWeixinCacheMemcached());//如果连接而配置未生效,不能这么使用 //微信的 Redis 缓存,如果不使用则注释掉(开启前必须保证配置有效,否则会抛错) if (useRedis) { app.UseSenparcWeixinCacheRedis(); } //app.UseWhen(h => useRedis, a => a.UseSenparcWeixinCacheRedis());//如果连接而配置未生效,不能这么使用 #endregion //开始注册微信信息 register.UseSenparcWeixin(senparcWeixinSetting.Value, isDebug /*此处为单独用于微信的调试状态*/, () => GetExContainerCacheStrategies(senparcWeixinSetting.Value)) //注意:这里没有 ; 下面可接着写 #region 注册公众号或小程序(按需) //注册公众号 .RegisterMpAccount( senparcWeixinSetting.Value.WeixinAppId, senparcWeixinSetting.Value.WeixinAppSecret, "【盛派网络小助手】公众号") //注册多个公众号或小程序 .RegisterMpAccount( senparcWeixinSetting.Value.WxOpenAppId, senparcWeixinSetting.Value.WxOpenAppSecret, "【盛派互动】小程序") #endregion #region 注册企业号(按需) //注册企业号 .RegisterWorkAccount( senparcWeixinSetting.Value.WeixinCorpId, senparcWeixinSetting.Value.WeixinCorpSecret, "【盛派网络】企业微信") //还可注册任意多个企业号 #endregion #region 注册微信支付(按需) //注册旧微信支付版本(V2) .RegisterTenpayOld(() => { //提供微信支付信息 var weixinPay_PartnerId = senparcWeixinSetting.Value.WeixinPay_PartnerId; var weixinPay_Key = senparcWeixinSetting.Value.WeixinPay_Key; var weixinPay_AppId = senparcWeixinSetting.Value.WeixinPay_AppId; var weixinPay_AppKey = senparcWeixinSetting.Value.WeixinPay_AppKey; var weixinPay_TenpayNotify = senparcWeixinSetting.Value.WeixinPay_TenpayNotify; var weixinPayInfo = new TenPayInfo(weixinPay_PartnerId, weixinPay_Key, weixinPay_AppId, weixinPay_AppKey, weixinPay_TenpayNotify); return(weixinPayInfo); }) //注册最新微信支付版本(V3) .RegisterTenpayV3(() => { //提供微信支付信息 var tenPayV3_MchId = senparcWeixinSetting.Value.TenPayV3_MchId; var tenPayV3_Key = senparcWeixinSetting.Value.TenPayV3_Key; var tenPayV3_AppId = senparcWeixinSetting.Value.TenPayV3_AppId; var tenPayV3_AppSecret = senparcWeixinSetting.Value.TenPayV3_AppSecret; var tenPayV3_TenpayNotify = senparcWeixinSetting.Value.TenPayV3_TenpayNotify; var tenPayV3Info = new TenPayV3Info(tenPayV3_AppId, tenPayV3_AppSecret, tenPayV3_MchId, tenPayV3_Key, tenPayV3_TenpayNotify); return(tenPayV3Info); }) #endregion #region 注册微信第三方平台(按需) .RegisterOpenComponent( senparcWeixinSetting.Value.Component_Appid, senparcWeixinSetting.Value.Component_Secret, //getComponentVerifyTicketFunc componentAppId => { var dir = Path.Combine(Server.GetMapPath("~/App_Data/OpenTicket")); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var file = Path.Combine(dir, string.Format("{0}.txt", componentAppId)); using (var fs = new FileStream(file, FileMode.Open)) { using (var sr = new StreamReader(fs)) { var ticket = sr.ReadToEnd(); return(ticket); } } }, //getAuthorizerRefreshTokenFunc (componentAppId, auhtorizerId) => { var dir = Path.Combine(Server.GetMapPath("~/App_Data/AuthorizerInfo/" + componentAppId)); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId)); if (!File.Exists(file)) { return(null); } using (Stream fs = new FileStream(file, FileMode.Open)) { var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); var result = (RefreshAuthorizerTokenResult)binFormat.Deserialize(fs); return(result.authorizer_refresh_token); } }, //authorizerTokenRefreshedFunc (componentAppId, auhtorizerId, refreshResult) => { var dir = Path.Combine(Server.GetMapPath("~/App_Data/AuthorizerInfo/" + componentAppId)); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId)); using (Stream fs = new FileStream(file, FileMode.Create)) { //这里存了整个对象,实际上只存RefreshToken也可以,有了RefreshToken就能刷新到最新的AccessToken var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); binFormat.Serialize(fs, refreshResult); fs.Flush(); } }, "【盛派网络】开放平台") #endregion ; /* 微信配置结束 */ #endregion }
/// <summary> /// 微信支付异步通知 /// </summary> /// <returns></returns> public IActionResult notify() { XTrace.WriteLine("微信支付异步通知开始:"); try { ResponseHandler resHandler = new ResponseHandler(null); string return_code = resHandler.GetParameter("return_code"); string return_msg = resHandler.GetParameter("return_msg"); //配置 Core.Config cfg = Core.Config.GetSystemConfig(); string appId = cfg.WXAppId; // ConfigurationManager.AppSettings["WeixinAppId"]; string appSecrect = cfg.WXAppSecret; // ConfigurationManager.AppSettings["WeixinAppSecrect"]; string wxmchId = cfg.MCHId; // ConfigurationManager.AppSettings["WeixinMCHId"]; string wxmchKey = cfg.MCHKey; // ConfigurationManager.AppSettings["WeixinMCHKey"]; TenPayV3Info TenPayV3Info = new TenPayV3Info(appId, appSecrect, wxmchId, wxmchKey, Utils.GetServerUrl() + "/wxpayment/notify", Utils.GetServerUrl() + "/wxpayment/notify"); string res = null; resHandler.SetKey(TenPayV3Info.Key); //验证请求是否从微信发过来(安全) if (resHandler.IsTenpaySign() && return_code.ToUpper() == "SUCCESS") { res = "success"; //正确的订单处理 //直到这里,才能认为交易真正成功了,可以进行数据库操作,但是别忘了返回规定格式的消息! string out_trade_no = resHandler.GetParameter("out_trade_no"); //商户订单号 XTrace.WriteLine("微信异步通知订单号:" + out_trade_no + ";" + JsonConvert.SerializeObject(resHandler)); OnlinePayOrder payOrder = OnlinePayOrder.Find(OnlinePayOrder._.PayOrderNum == out_trade_no); if (payOrder == null) { XTrace.WriteLine($"支付成功,但是支付订单不存在:{out_trade_no}"); res = "wrong";//错误的订单处理 } else { if (payOrder.PaymentStatus == Utils.PaymentState[0]) { //更新支付订单 payOrder.PaymentStatus = Utils.PaymentState[1]; payOrder.ReceiveTime = DateTime.Now; payOrder.IsOK = 1; payOrder.Update(); //获取订单 Order order = Order.Find(Order._.OrderNum == payOrder.OrderNum); if (order != null) { order.PaymentStatus = Utils.PaymentState[1]; order.PayType = "微信支付"; if (order.MyType == (int)Utils.MyType.分销商认证) { order.OrderStatus = Utils.OrdersState[2]; } order.Update(); //如果是属于升级会员的,那要修改会员状态 if (order.MyType == (int)Utils.MyType.分销商认证 && order.OrderType > 0) { Member he = Member.FindById(order.UId); if (he.RoleId != order.OrderType) { he.RoleId = order.OrderType; he.IsVerifySellers = 1; he.Update(); } } //写入订单记录 OrderLog log = new OrderLog(); log.AddTime = DateTime.Now; log.OrderId = order.Id; log.OrderNum = order.OrderNum; log.UId = order.UId; log.Actions = "微信支付成功;订单号:" + order.OrderNum + ";金额:" + order.TotalPay.ToString("N2"); log.Insert(); } } } } else { res = "wrong";//错误的订单处理 } #region 记录日志 XTrace.WriteLine($"微信支付回调处理结果:{res}"); #endregion string xml = string.Format(@"<xml> <return_code><![CDATA[{0}]]></return_code> <return_msg><![CDATA[{1}]]></return_msg> </xml>", return_code, return_msg); return(Content(xml, "text/xml")); } catch (Exception ex) { new WeixinException(ex.Message, ex); throw; } }
public ReJson DoPayOrder(string ordernum, string random = "", string timeStamp = "", string signature = "") { //获取订单 Order entity = Order.Find(Order._.OrderNum == ordernum); if (entity == null) { //reJson.code = 40000; //reJson.message = "系统找不到本订单!"; //return reJson; return(new ReJson(40000, "系统找不到本订单!")); } //判断订单状态 if (entity.OrderStatus == Utils.OrdersState[3]) { //reJson.code = 40000; //reJson.message = "已完成订单不允许支付!"; //return reJson; return(new ReJson(40000, "已完成订单不允许支付!")); } if (entity.PaymentStatus != Utils.PaymentState[0]) { //reJson.code = 40000; //reJson.message = "当前订单支付状态不允许支付!"; //return reJson; return(new ReJson(40000, "当前订单支付状态不允许支付!")); } //获取用户并判断是否是已经注册用户 Member my = Member.FindById(entity.UId); if (my == null || string.IsNullOrEmpty(my.WeixinAppOpenId)) { //reJson.code = 40000; //reJson.message = "用户状态错误,无法使用本功能!"; //return reJson; return(new ReJson(40000, "用户状态错误,无法使用本功能!")); } //开始生成支付订单 OnlinePayOrder model = new OnlinePayOrder(); model.OrderId = entity.Id; model.OrderNum = entity.OrderNum; model.PayId = 1; model.PaymentNotes = "微信支付"; model.PaymentStatus = Utils.PaymentState[0]; model.PayOrderNum = Utils.GetOrderNum();//在线支付订单的订单号 model.PayType = "微信支付"; model.TotalPrice = entity.TotalPay; model.TotalQty = entity.TotalQty; model.UId = entity.UId; model.IP = Utils.GetIP(); model.IsOK = 0; model.AddTime = DateTime.Now; model.Insert(); //写入日志 OrderLog log = new OrderLog(); log.AddTime = DateTime.Now; log.OrderId = entity.Id; log.OrderNum = entity.OrderNum; log.UId = entity.UId; log.Actions = "用户使用微信支付;支付订单号:" + model.PayOrderNum; log.Insert(); Core.Config cfg = Core.Config.GetSystemConfig(); string appId = cfg.WXAppId; // ConfigurationManager.AppSettings["WeixinAppId"]; string appSecrect = cfg.WXAppSecret; // ConfigurationManager.AppSettings["WeixinAppSecrect"]; string wxmchId = cfg.MCHId; // ConfigurationManager.AppSettings["WeixinMCHId"]; string wxmchKey = cfg.MCHKey; // ConfigurationManager.AppSettings["WeixinMCHKey"]; TenPayV3Info TenPayV3Info = new TenPayV3Info(appId, appSecrect, wxmchId, wxmchKey, Utils.GetServerUrl() + "/wxpayment/notify", Utils.GetServerUrl() + "/wxpayment/notify"); TenPayV3Info.TenPayV3Notify = Utils.GetServerUrl() + "/wxpayment/notify"; XTrace.WriteLine("微信支付异步通知地址:" + TenPayV3Info.TenPayV3Notify); //创建支付应答对象 RequestHandler packageReqHandler = new RequestHandler(null); var sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(26);//最多32位 var nonceStr = TenPayV3Util.GetNoncestr(); string rtimeStamp = Utils.GetTimeStamp(); //创建请求统一订单接口参数 var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, entity.Title, model.PayOrderNum, (int)(entity.TotalPay * 100), Utils.GetIP(), TenPayV3Info.TenPayV3Notify, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, my.WeixinAppOpenId, TenPayV3Info.Key, nonceStr); //返回给微信的请求 RequestHandler res = new RequestHandler(null); try { //调用统一订单接口 var result = TenPayV3.Unifiedorder(xmlDataInfo); XTrace.WriteLine("微信支付统一下单返回:" + JsonConvert.SerializeObject(result)); if (result.return_code == "FAIL") { //reJson.code = 40005; //reJson.message = result.return_msg; //return reJson; return(new ReJson(40005, result.return_msg)); } string nativeReqSign = res.CreateMd5Sign("key", TenPayV3Info.Key); //https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3 //paySign = MD5(appId=wxd678efh567hg6787&nonceStr=5K8264ILTKCH16CQ2502SI8ZNMTM67VS&package=prepay_id=wx2017033010242291fcfe0db70013231072&signType=MD5&timeStamp=1490840662&key=qazwsxedcrfvtgbyhnujmikolp111111) string paySign = Utils.MD5($"appId={TenPayV3Info.AppId}&nonceStr={nonceStr}&package=prepay_id={result.prepay_id}&signType=MD5&timeStamp={rtimeStamp}&key={TenPayV3Info.Key}").ToUpper(); string package = $"prepay_id={result.prepay_id}"; dynamic detail = new { timeStamp = rtimeStamp, nonceStr = nonceStr, package = package, signType = "MD5", paySign = paySign }; //reJson.code = 0; //reJson.message = "下单成功!"; //reJson.detail = detail; //return reJson; return(new ReJson(40000, "下单成功!", detail)); } catch (Exception ex) { res.SetParameter("return_code", "FAIL"); res.SetParameter("return_msg", "统一下单失败"); XTrace.WriteLine($"统一下单失败:{ex.Message}"); //reJson.code = 40005; //reJson.message = "统一下单失败,请联系管理员!"; return(new ReJson(40005, "统一下单失败,请联系管理员!")); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions <SenparcSetting> senparcSetting, IOptions <SenparcWeixinSetting> senparcWeixinSetting) { //引入EnableRequestRewind中间件 app.UseEnableRequestRewind(); app.UseSession(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); #region 提供网站根目录(当前 Sample 用到,和 SDK 无关) if (env.ContentRootPath != null) { Senparc.Weixin.MP.Sample.CommonService.Utilities.Server.AppDomainAppPath = env.ContentRootPath; // env.ContentRootPath; } Senparc.Weixin.MP.Sample.CommonService.Utilities.Server.WebRootPath = env.WebRootPath; // env.ContentRootPath; #endregion // 启动 CO2NET 全局注册,必须! IRegisterService register = RegisterService.Start(env, senparcSetting.Value) //关于 UseSenparcGlobal() 的更多用法见 CO2NET Demo:https://github.com/Senparc/Senparc.CO2NET/blob/master/Sample/Senparc.CO2NET.Sample.netcore/Startup.cs .UseSenparcGlobal(); //如果需要自动扫描自定义扩展缓存,可以这样使用: //register.UseSenparcGlobal(true); //如果需要指定自定义扩展缓存,可以这样用: //register.UseSenparcGlobal(false, GetExCacheStrategies); #region CO2NET 全局配置 #region 全局缓存配置(按需) //当同一个分布式缓存同时服务于多个网站(应用程序池)时,可以使用命名空间将其隔离(非必须) register.ChangeDefaultCacheNamespace("DefaultCO2NETCache"); #region 配置和使用 Redis //配置全局使用Redis缓存(按需,独立) var redisConfigurationStr = senparcSetting.Value.Cache_Redis_Configuration; var useRedis = !string.IsNullOrEmpty(redisConfigurationStr) && redisConfigurationStr != "Redis配置"; if (useRedis)//这里为了方便不同环境的开发者进行配置,做成了判断的方式,实际开发环境一般是确定的,这里的if条件可以忽略 { /* 说明: * 1、Redis 的连接字符串信息会从 Config.SenparcSetting.Cache_Redis_Configuration 自动获取并注册,如不需要修改,下方方法可以忽略 * /* 2、如需手动修改,可以通过下方 SetConfigurationOption 方法手动设置 Redis 链接信息(仅修改配置,不立即启用) */ Senparc.CO2NET.Cache.Redis.Register.SetConfigurationOption(redisConfigurationStr); //以下会立即将全局缓存设置为 Redis Senparc.CO2NET.Cache.Redis.Register.UseKeyValueRedisNow();//键值对缓存策略(推荐) //Senparc.CO2NET.Cache.Redis.Register.UseHashRedisNow();//HashSet储存格式的缓存策略 //也可以通过以下方式自定义当前需要启用的缓存策略 //CacheStrategyFactory.RegisterObjectCacheStrategy(() => RedisObjectCacheStrategy.Instance);//键值对 //CacheStrategyFactory.RegisterObjectCacheStrategy(() => RedisHashSetObjectCacheStrategy.Instance);//HashSet } //如果这里不进行Redis缓存启用,则目前还是默认使用内存缓存 #endregion #region 配置和使用 Memcached //配置Memcached缓存(按需,独立) var memcachedConfigurationStr = senparcSetting.Value.Cache_Memcached_Configuration; var useMemcached = !string.IsNullOrEmpty(memcachedConfigurationStr) && memcachedConfigurationStr != "Memcached配置"; if (useMemcached) //这里为了方便不同环境的开发者进行配置,做成了判断的方式,实际开发环境一般是确定的,这里的if条件可以忽略 { app.UseEnyimMemcached(); /* 说明: * 1、Memcached 的连接字符串信息会从 Config.SenparcSetting.Cache_Memcached_Configuration 自动获取并注册,如不需要修改,下方方法可以忽略 * /* 2、如需手动修改,可以通过下方 SetConfigurationOption 方法手动设置 Memcached 链接信息(仅修改配置,不立即启用) */ Senparc.CO2NET.Cache.Memcached.Register.SetConfigurationOption(redisConfigurationStr); //以下会立即将全局缓存设置为 Memcached Senparc.CO2NET.Cache.Memcached.Register.UseMemcachedNow(); //也可以通过以下方式自定义当前需要启用的缓存策略 CacheStrategyFactory.RegisterObjectCacheStrategy(() => MemcachedObjectCacheStrategy.Instance); } #endregion #endregion #region 注册日志(按需,建议) register.RegisterTraceLog(ConfigTraceLog);//配置TraceLog #endregion #endregion #region 微信相关配置 /* 微信配置开始 * * 建议按照以下顺序进行注册,尤其须将缓存放在第一位! */ //注册开始 #region 微信缓存(按需,必须在 register.UseSenparcWeixin() 之前) // 微信的 Memcached 缓存,如果不使用则注释掉(开启前必须保证配置有效,否则会抛错) if (useMemcached) { app.UseSenparcWeixinCacheMemcached(); } //微信的 Redis 缓存,如果不使用则注释掉(开启前必须保证配置有效,否则会抛错) if (useRedis) { app.UseSenparcWeixinCacheRedis(); } #endregion //开始注册微信信息,必须! register.UseSenparcWeixin(senparcWeixinSetting.Value, senparcSetting.Value) //注意:上一行没有 ; 下面可接着写 .RegisterXX() #region 注册公众号或小程序(按需) //注册公众号 .RegisterMpAccount( senparcWeixinSetting.Value.WeixinAppId, senparcWeixinSetting.Value.WeixinAppSecret, "【盛派网络小助手】公众号") //注册多个公众号或小程序 .RegisterMpAccount( senparcWeixinSetting.Value.WxOpenAppId, senparcWeixinSetting.Value.WxOpenAppSecret, "【盛派网络小助手】小程序") //注意:小程序和公众号的AppId/Secret属于并列关系,这里name需要区分开 //除此以外,仍然可以在程序任意地方注册公众号或小程序: //AccessTokenContainer.Register(appId, appSecret, name);//命名空间:Senparc.Weixin.MP.Containers #endregion #region 注册企业号(按需) //注册企业微信 .RegisterWorkAccount( senparcWeixinSetting.Value.WeixinCorpId, senparcWeixinSetting.Value.WeixinCorpSecret, "【盛派网络】企业微信") //还可注册任意多个企业号 //除此以外,仍然可以在程序任意地方注册企业微信: //AccessTokenContainer.Register(corpId, corpSecret, name);//命名空间:Senparc.Weixin.Work.Containers #endregion #region 注册微信支付(按需) //注册旧微信支付版本(V2) .RegisterTenpayOld(() => { //提供微信支付(旧版本)信息 var weixinPayInfo = new TenPayInfo(senparcWeixinSetting.Value); return(weixinPayInfo); }, "【盛派网络小助手】公众号"//这里的 name 和第一个 RegisterMpAccount() 中的一致,会被记录到同一个 SenparcWeixinSettingItem 对象中 ) //注册最新微信支付版本(V3) .RegisterTenpayV3(() => { //提供微信支付(新版本 V3)信息 var tenPayV3Info = new TenPayV3Info(senparcWeixinSetting.Value); return(tenPayV3Info); }, "【盛派网络小助手】公众号") //记录到同一个 SenparcWeixinSettingItem 对象中 #endregion #region 注册微信第三方平台(按需) .RegisterOpenComponent( senparcWeixinSetting.Value.Component_Appid, senparcWeixinSetting.Value.Component_Secret, //getComponentVerifyTicketFunc componentAppId => { var dir = Path.Combine(Server.GetMapPath("~/App_Data/OpenTicket")); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var file = Path.Combine(dir, string.Format("{0}.txt", componentAppId)); using (var fs = new FileStream(file, FileMode.Open)) { using (var sr = new StreamReader(fs)) { var ticket = sr.ReadToEnd(); return(ticket); } } }, //getAuthorizerRefreshTokenFunc (componentAppId, auhtorizerId) => { var dir = Path.Combine(Server.GetMapPath("~/App_Data/AuthorizerInfo/" + componentAppId)); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId)); if (!File.Exists(file)) { return(null); } using (Stream fs = new FileStream(file, FileMode.Open)) { var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); var result = (RefreshAuthorizerTokenResult)binFormat.Deserialize(fs); return(result.authorizer_refresh_token); } }, //authorizerTokenRefreshedFunc (componentAppId, auhtorizerId, refreshResult) => { var dir = Path.Combine(Server.GetMapPath("~/App_Data/AuthorizerInfo/" + componentAppId)); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId)); using (Stream fs = new FileStream(file, FileMode.Create)) { //这里存了整个对象,实际上只存RefreshToken也可以,有了RefreshToken就能刷新到最新的AccessToken var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); binFormat.Serialize(fs, refreshResult); fs.Flush(); } }, "【盛派网络】开放平台") //除此以外,仍然可以在程序任意地方注册开放平台: //ComponentContainer.Register();//命名空间:Senparc.Weixin.Open.Containers #endregion ; /* 微信配置结束 */ #endregion }