/** * * 从统一下单成功返回的数据中获取微信浏览器调起jsapi支付所需的参数, * 微信浏览器调起JSAPI时的输入参数格式如下: * { * "appId" : "wx2421b1c4370ec43b", //公众号名称,由商户传入 * "timeStamp":" 1395712654", //时间戳,自1970年以来的秒数 * "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串 * "package" : "prepay_id=u802345jgfjsdfgsdg888", * "signType" : "MD5", //微信签名方式: * "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名 * } * @return string 微信浏览器调起JSAPI时的输入参数,json格式可以直接做参数用 * 更详细的说明请参考网页端调起支付API:http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7 * */ public string GetJsApiParameters() { LogHelper.Debug(this.GetType().ToString(), "JsApiPay::GetJsApiParam is processing..."); WxPayData jsApiParam = new WxPayData(); jsApiParam.SetValue("appId", unifiedOrderResult.GetValue("appid")); jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp()); jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr()); jsApiParam.SetValue("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id")); jsApiParam.SetValue("signType", "MD5"); jsApiParam.SetValue("paySign", jsApiParam.MakeSign()); string parameters = jsApiParam.ToJson(); LogHelper.Debug(this.GetType().ToString(), "Get jsApiParam : " + parameters); return(parameters); }
/** * 生成扫描支付模式一URL * @param productId 商品ID * @return 模式一URL */ public string GetPrePayUrl(string productId, string AdminHotelid, int Hotelid = 0) { Log.Info(this.GetType().ToString(), "Native pay mode 1 url is producing..."); WxPayData data = new WxPayData(); data.SetValue("appid", WxPayConfig.APPID(AdminHotelid, Hotelid)); //公众帐号id data.SetValue("mch_id", WxPayConfig.MCHID(AdminHotelid, Hotelid)); //商户号 data.SetValue("time_stamp", WxPayApi.GenerateTimeStamp()); //时间戳 data.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); //随机字符串 data.SetValue("product_id", productId); //商品ID data.SetValue("sign", data.MakeSign(AdminHotelid, Hotelid)); //签名 string str = ToUrlParams(data.GetValues()); //转换为URL串 string url = "weixin://wxpay/bizpayurl?" + str; Log.Info(this.GetType().ToString(), "Get native pay mode 1 url : " + url); return(url); }
/// <summary> /// 商家活动 /// </summary> /// <returns></returns> public ActionResult ActList() { var model = new List <Tuple <string, string, string, DateTime, DateTime, bool, TargetCode> >(); var kanjiaList = IKanJiaService.GetList(x => x.UserID == LoginUser.ID).Select(x => { return(new Tuple <string, string, string, DateTime, DateTime, bool, TargetCode>(x.Name, x.Picture, x.ID, x.StartTime, x.EndTime, x.IsDelete, TargetCode.Kanjia)); }).ToList(); if (kanjiaList != null && kanjiaList.Count > 0) { model.AddRange(kanjiaList); } var pintuanList = IPinTuanService.GetList(x => x.UserID == LoginUser.ID); pintuanList.ForEach(x => { model.Add(new Tuple <string, string, string, DateTime, DateTime, bool, TargetCode>(x.Name, x.Picture, x.ID, x.StartTime, x.EndTime, x.IsDelete, TargetCode.Pintuan)); }); var miaoshaList = IMiaoShaService.GetList(x => x.UserID == LoginUser.ID); miaoshaList.ForEach(x => { model.Add(new Tuple <string, string, string, DateTime, DateTime, bool, TargetCode>(x.Name, x.Picture, x.ID, x.StartTime, x.EndTime, x.IsDelete, TargetCode.Miaosha)); }); var pintuList = IPinTuService.GetList(x => x.UserID == LoginUser.ID); pintuList.ForEach(x => { model.Add(new Tuple <string, string, string, DateTime, DateTime, bool, TargetCode>(x.Name, x.Picture, x.ID, x.StartTime, x.EndTime, x.IsDelete, TargetCode.Pintu)); }); ViewBag.AppId = Params.WeixinAppId; string cacheToken = WxPayApi.GetCacheToken(Params.WeixinAppId, Params.WeixinAppSecret); ViewBag.TimeStamp = WxPayApi.GenerateTimeStamp(); ViewBag.NonceStr = WxPayApi.GenerateNonceStr(); ViewBag.Signature = WxPayApi.GetSignature(Request.Url.ToString().Split('#')[0], cacheToken, ViewBag.TimeStamp, ViewBag.NonceStr); ViewBag.List = model.OrderByDescending(x => x.Item4).ToList(); return(View()); }
/// <summary> /// 生成扫描支付模式一URL /// </summary> /// <param name="productId">商品ID</param> /// <returns>模式一URL</returns> public string GetPrePayUrl(string productId) { LogHelper.Info(this.GetType().ToString(), "Native pay mode 1 url is producing..."); WxPayData data = new WxPayData(); data.SetValue("appid", WxPayConfig.AppId); //公众帐号id data.SetValue("mch_id", WxPayConfig.MchId); //商户号 data.SetValue("time_stamp", WxPayApi.GenerateTimeStamp()); //时间戳 data.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); //随机字符串 data.SetValue("product_id", productId); //商品ID data.SetValue("sign", data.MakeSign()); //签名 string str = ToUrlParams(data.GetValues()); //转换为URL串 string url = "weixin://wxpay/bizpayurl?" + str; //weixin://wxpay/bizpayurl?appid=wx426b3015555a46be&mch_id=1900009851&nonce_str=lz2gmz19sbeteufbg2onmbt9sabv0kef&product_id=123456789&time_stamp=1531917401&sign=69C6AEFFF6943AADCF84C4FA372BE60D LogHelper.Info(this.GetType().ToString(), "Get native pay mode 1 url : " + url); return(url); }
public WxPayData getToken(string contract_id, string city, string qrcode_hashs, int token_count = 1) { string url = "https://api.mch.weixin.qq.com/transit/gettoken"; WxPayData data = new WxPayData(); data.SetValue("appid", WxPayConfig.APPID(city)); data.SetValue("mch_id", WxPayConfig.getMCHID(city)); data.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); data.SetValue("contract_id", contract_id); data.SetValue("sign_type", "HMAC-SHA256"); data.SetValue("sign", data.MakeSign_SHA256()); data.SetValue("token_count", token_count); data.SetValue("qrcode_hashs", qrcode_hashs); string xml = HttpService.Post(data.ToXml(), url, false, 10); WxPayData res = new WxPayData(); res.FromXml(xml); return(res); }
/// <summary> /// 秒杀页面 /// </summary> /// <param name="id"></param> /// <returns></returns> public ActionResult MiaoSha(string id) { var model = IMiaoShaService.Find(id); if (model == null) { return(Forbidden()); } model.ClickCount++; IMiaoShaService.Update(model); ViewBag.AppId = Params.WeixinAppId; string cacheToken = WxPayApi.GetCacheToken(Params.WeixinAppId, Params.WeixinAppSecret); ViewBag.TimeStamp = WxPayApi.GenerateTimeStamp(); ViewBag.NonceStr = WxPayApi.GenerateNonceStr(); ViewBag.Signature = WxPayApi.GetSignature(Request.Url.ToString().Split('#')[0], cacheToken, ViewBag.TimeStamp, ViewBag.NonceStr); ViewBag.IsReport = IUserActivityService.IsExits(x => x.TargetID == id && x.JoinUserID == LoginUser.ID); return(View(model)); }
public string H5Pay(string subject, string body, string notifyUrl, string returnUrl, PayLog payLog, Payment payment, Dictionary <string, string> param = null) { var config = _configService.Get <WeiXinConfig>(); WxPayData data = new WxPayData(); data.SetValue("body", body); data.SetValue("out_trade_no", payLog.TransactionNo); data.SetValue("total_fee", Convert.ToInt32(payLog.OrderAmount * 100)); data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss")); data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss")); data.SetValue("goods_tag", body); data.SetValue("trade_type", "WAP"); data.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); data.SetValue("notify_url", notifyUrl); WeiXinPayConfig weiXinPayConfig = new WeiXinPayConfig() { APPID = config.AppId, MCHID = config.MchId, KEY = config.Key }; WxPayData result = WxPayApi.UnifiedOrder(data, 6, weiXinPayConfig); if (result.GetValue("return_code").ToString().Equals("fail", StringComparison.OrdinalIgnoreCase)) { return(result.GetValue("return_msg").ToString()); } WxPayData reSignWxPayData = new WxPayData(); reSignWxPayData.SetValue("appid", result.GetValue("appid")); reSignWxPayData.SetValue("partnerid", result.GetValue("mch_id")); reSignWxPayData.SetValue("prepayid", result.GetValue("prepay_id")); reSignWxPayData.SetValue("noncestr", result.GetValue("nonce_str")); reSignWxPayData.SetValue("timestamp", WxPayApi.GenerateTimeStamp()); reSignWxPayData.SetValue("package", "WAP"); reSignWxPayData.SetValue("sign", reSignWxPayData.MakeSign(weiXinPayConfig.KEY)); var deepLink = $"weixin://wap/pay?{HttpUtility.UrlEncode(reSignWxPayData.ToUrl())}"; return($"<script>location.href='{deepLink}';</script>"); }
// GET: User public ActionResult BuyTime() { if (LoginUser == null) { return(Redirect("/login/index?redirect_uri=" + this.Request.Url.ToString())); } var user = IUserService.Find(LoginUser.ID); if (user.Password.IsNullOrEmpty()) { return(RedirectToAction("PersonData", "user")); } ViewBag.AppId = Params.WeixinAppId; string cacheToken = WxPayApi.GetCacheToken(Params.WeixinAppId, Params.WeixinAppSecret); ViewBag.TimeStamp = WxPayApi.GenerateTimeStamp(); ViewBag.NonceStr = WxPayApi.GenerateNonceStr(); ViewBag.Signature = WxPayApi.GetSignature(Params.SiteUrl, cacheToken, ViewBag.TimeStamp, ViewBag.NonceStr); return(View(IRechargePlanService.GetList())); }
private static void SDK_Config(HttpContext context) { JS_SDKModel model = new JS_SDKModel(); try { var windowurl = context.Request["windowurl"]; var action = context.Request["action"]; LogTextHelper.Log("action:" + action + " windowurl_1:" + windowurl); WxPayData jsApiParam = new WxPayData(); model.appId = WeChatConfig.AppId; model.timeStamp = WxPayApi.GenerateTimeStamp(); model.nonceStr = WxPayApi.GenerateNonceStr(); model.ticket = string.Empty; //获取jsapi_ticket if (HttpRuntime.Cache["JsApiTicket"] == null) { model.ticket = WxPayApi.initJSAPITicket(); } model.ticket = HttpRuntime.Cache["JsApiTicket"] as string; if (string.IsNullOrEmpty(model.ticket)) { model.ticket = WxPayApi.initJSAPITicket(); } //构造需要用SHA1算法加密的数据 WxPayData signData = new WxPayData(); signData.SetValue("noncestr", model.nonceStr); signData.SetValue("jsapi_ticket", model.ticket); signData.SetValue("timestamp", model.timeStamp); signData.SetValue("url", windowurl); string param = signData.ToUrl(); model.signature = FormsAuthentication.HashPasswordForStoringInConfigFile(param, "SHA1"); } catch (Exception ex) { model.status = 0; model.msg = ex.Message; LogTextHelper.Log(ex.ToString()); } context.Response.Write(JsonConvert.SerializeObject(model)); }
/** * * 从统一下单成功返回的数据中获取微信浏览器调起jsapi支付所需的参数, * 微信浏览器调起JSAPI时的输入参数格式如下: * { * "appId" : "wx2421b1c4370ec43b", //公众号名称,由商户传入 * "timeStamp":" 1395712654", //时间戳,自1970年以来的秒数 * "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串 * "package" : "prepay_id=u802345jgfjsdfgsdg888", * "signType" : "MD5", //微信签名方式: * "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名 * } * @return string 微信浏览器调起JSAPI时的输入参数,json格式可以直接做参数用 * 更详细的说明请参考网页端调起支付API:http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7 * */ public string GetJsApiParameters(string appId) { var WxPayConfig = Configuration.GetAppPayConfig <Config.Sections.Pay.WXPay>(appId); Log.Debug(this.GetType().ToString(), "JsApiPay::GetJsApiParam is processing..."); WxPayData jsApiParam = new WxPayData(); jsApiParam.SetValue("appId", unifiedOrderResult.GetValue("appid")); jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp()); jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr()); jsApiParam.SetValue("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id")); jsApiParam.SetValue("signType", "MD5"); jsApiParam.SetValue("paySign", jsApiParam.MakeSign(WxPayConfig.KEY)); string parameters = jsApiParam.ToJson(); Log.Debug(this.GetType().ToString(), "Get jsApiParam : " + parameters); return(parameters); }
public void Set() { // Load(); //if(Account!=null) //{ // ImageUrl = Account.qrCodeUrl; //} //appId = WxPayConfig.APPID; // var access_token = AccessTokenContainer.GetToken(WxPayConfig.APPID); var jsapi_ticket = Senparc.Weixin.MP.CommonAPIs.CommonApi.GetTicket(WxPayConfig.APPID, WxPayConfig.APPSECRET).ticket; timestamp = WxPayApi.GenerateTimeStamp(); nonceStr = WxPayApi.GenerateNonceStr(); WxPayData jsApiParam = new WxPayData(); jsApiParam.SetValue("noncestr", nonceStr); jsApiParam.SetValue("jsapi_ticket", jsapi_ticket); jsApiParam.SetValue("timestamp", timestamp); jsApiParam.SetValue("url", url); signature = jsApiParam.SHA1_Hash(); }
public JsonResult GetPaySign(string openid) { string nonceStr = WxPayApi.GenerateNonceStr(); //随机字符串,不长于32位 string outTradeNo = WxPayApi.GenerateOutTradeNo(); //订单号:32个字符内、不得重复 string spbillCreateIp = WxPayConfig.GetIP(System.Web.HttpContext.Current); //用户端IP int total_fee = 1; //订单金额(单位:分),整数 string trade_type = "JSAPI"; //JSAPI,NATIVE,APP,WAP #region 调用统一支付接口获得prepay_id(预支付交易会话标识) WxPayData wxPayData = new WxPayData(); wxPayData.SetValue("appid", WxPayConfig.APPID); //appid wxPayData.SetValue("body", WxPayConfig.BODY); //支付描述 wxPayData.SetValue("mch_id", WxPayConfig.MCHID); //商户id wxPayData.SetValue("nonce_str", nonceStr); //随机字符串 wxPayData.SetValue("notify_url", WxPayConfig.NOTIFY_URL); //回调地址 wxPayData.SetValue("openid", openid); //openid wxPayData.SetValue("out_trade_no", outTradeNo); //订单号 wxPayData.SetValue("spbill_create_ip", spbillCreateIp); //客户端ip地址 wxPayData.SetValue("total_fee", total_fee.ToString()); //订单金额(单位:分),整数 wxPayData.SetValue("trade_type", trade_type); //交易类型 wxPayData.SetValue("sign", wxPayData.MakeSign()); //签名 string data = wxPayData.ToXml(); string prepayId = WeChatTools.UnifiedOrder(data); #endregion #region 支付参数 string timeStamp = WxPayApi.GenerateTimeStamp(); nonceStr = WxPayApi.GenerateNonceStr(); WxPayData wxPaySign = new WxPayData(); wxPaySign.SetValue("appId", WxPayConfig.APPID); wxPaySign.SetValue("timeStamp", timeStamp); wxPaySign.SetValue("nonceStr", nonceStr); wxPaySign.SetValue("package", string.Format("prepay_id={0}", prepayId)); wxPaySign.SetValue("signType", "MD5"); string paysign = wxPaySign.MakeSign(); wxPaySign.SetValue("paySign", paysign); #endregion return(Json(new { data = wxPaySign.GetValues(), openid = openid }, JsonRequestBehavior.AllowGet)); }
WxPayData GetUnifiedOrderResult() { string url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; //统一下单 WxPayData data = new WxPayData(); data.SetValue("body", "test"); data.SetValue("attach", "test"); data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo()); data.SetValue("notify_url", "http://demo.xmpharos.com/WXNotify.aspx"); data.SetValue("total_fee", 1); data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss")); data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss")); data.SetValue("goods_tag", "test"); data.SetValue("trade_type", "JSAPI"); data.SetValue("openid", "oAZCps75h8Jyj1a0uyIktHiGHbho"); data.SetValue("spbill_create_ip", WxPayConfig.IP); //终端ip data.SetValue("appid", "wxbeb2e5a46ca7bf69"); //公众账号ID data.SetValue("mch_id", "1240541002"); //商户号 data.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); //随机字符串,放置顺序 //签名 data.SetValue("sign", data.MakeSign("e10adc3849ba56abbe56e056f2588888")); string xml = data.ToXml(); var start = DateTime.Now; Log.Debug("WxPayApi", "UnfiedOrder request : " + xml); string response = HttpService.Post(xml, url, false, 10); Log.Debug("WxPayApi", "UnfiedOrder response : " + response); WxPayData result = new WxPayData(); result.FromXml(response); if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "") { Log.Error(this.GetType().ToString(), "UnifiedOrder response error!"); throw new Exception("UnifiedOrder response error!"); } return(result); }
/// <summary> /// 提交资料 /// </summary> /// <param name="inputObj"></param> /// <returns></returns> public static string Submit(WxPayData inputObj) { //WxPayData inputObj = new WxPayData(); inputObj.SetValue("version", "2.0"); //接口版本号 inputObj.SetValue("mch_id", Lib.Config.MchId); //商户号 inputObj.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); //随机字符串 //检测必填参数 CheckParams(inputObj); AccountNumberIsSupport(inputObj.GetValue("account_number").ToString()); ////敏感信息加密 inputObj.SetValue("cert_sn", Certificates.Get().data.FirstOrDefault().serial_no); //平台证书序列号 inputObj.SetValue("id_card_name", InfoEncryption(inputObj.GetValue("id_card_name").ToString())); //身份证姓名 inputObj.SetValue("id_card_number", InfoEncryption(inputObj.GetValue("id_card_number").ToString())); //身份证 inputObj.SetValue("account_name", InfoEncryption(inputObj.GetValue("account_name").ToString())); //开户名称 inputObj.SetValue("account_number", InfoEncryption(inputObj.GetValue("account_number").ToString())); //银行账号 inputObj.SetValue("contact", InfoEncryption(inputObj.GetValue("contact").ToString())); //联系人姓名 inputObj.SetValue("contact_phone", InfoEncryption(inputObj.GetValue("contact_phone").ToString())); //手机号码 inputObj.SetValue("sign_type", WxPayData.SIGN_TYPE_HMAC_SHA256); //签名类型 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); string url = "https://api.mch.weixin.qq.com/applyment/micro/submit"; int timeOut = 10; Log.Debug("申请入驻", "request : " + xml); //调用HTTP通信接口以提交数据到API string response = HttpService.Post(xml, url, true, timeOut); Log.Debug("申请入驻", "response : " + response); return(response); }
private string MakeJsSign(string appId, string ticket) { string timeStamp = WxPayApi.GenerateTimeStamp(); string onceStr = WxPayApi.GenerateNonceStr(); string signature = string.Empty; WxPayData jsApiParam = new WxPayData(); jsApiParam.SetValue("appId", appId); jsApiParam.SetValue("timestamp", timeStamp); jsApiParam.SetValue("nonceStr", onceStr); //jsApiParam.SetValue("signature", signature); //string keys = string.Format("jsapi_ticket={0}&noncestr={1}×tamp={2}&url={3}", ticket,onceStr,timeStamp, PathConfig.DomainConfig+"/wechat.html"); Dictionary <string, string> dicParam = new Dictionary <string, string>(); dicParam["jsapi_ticket"] = ticket; dicParam["noncestr"] = onceStr; dicParam["timestamp"] = timeStamp; dicParam["url"] = PathConfig.DomainConfig + "/wechat.html"; signature = Sha1(dicParam, Encoding.UTF8).ToLower(); jsApiParam.SetValue("signature", signature); return(jsApiParam.ToJson()); }
public void ProcessRequest(HttpContext context) { HttpRequest request = context.Request; Stream stream = request.InputStream; if (stream.Length != 0) { int total_fee = Convert.ToInt32(request["total_fee"]); string out_trade_no = request["out_trade_no"]; WxPayData data = new WxPayData(); data.SetValue("body", "微特众包-商家充值");//商品描述 //data.SetValue("attach", "test");//附加数据 //data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());//订单号 data.SetValue("out_trade_no", out_trade_no); //订单号 data.SetValue("total_fee", total_fee); //总金额 data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss")); //交易起始时间 data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss")); //交易结束时间 data.SetValue("trade_type", "APP"); //交易类型 WxPayData result = WxPayApi.UnifiedOrder(data); //调用统一下单接口 if (result.IsSet("prepay_id")) { WxPayData order = new WxPayData(); order.SetValue("appid", WxPayConfig.APPID); order.SetValue("partnerid", WxPayConfig.MCHID); order.SetValue("noncestr", WxPayApi.GenerateNonceStr()); order.SetValue("prepayid", result.GetValue("prepay_id")); order.SetValue("timestamp", WxPayApi.GenerateTimeStamp()); order.SetValue("package", "Sign=WXPay"); order.SetValue("sign", order.MakeSign()); context.Response.Write(order.ToJson()); } } else { context.Response.Write(""); } }
public string GetPayUrl(Order order, string ip) { if (order == null) { throw new ArgumentNullException("order"); } WxPayData data = new WxPayData(); data.SetValue("appid", WxPayConfig.APPID); data.SetValue("mch_id", WxPayConfig.MCHID); // data.SetValue("device_info", "iphone4s"); data.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); data.SetValue("body", "好油菜充值"); //商品描述 data.SetValue("detail", "好油菜充值"); //商品描述 data.SetValue("attach", "北京好油菜"); //附加数据 data.SetValue("out_trade_no", order.TradeNumber); //随机字符串 // data.SetValue("total_fee", Convert.ToInt32(order.OrderTotal * 100));//总金额 data.SetValue("total_fee", (int)order.Amount * 100); //总金额 // data.SetValue("spbill_create_ip",ip);//总金额 data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss")); //交易起始时间 data.SetValue("time_expire", DateTime.Now.AddMinutes(30).ToString("yyyyMMddHHmmss")); //交易结束时间 data.SetValue("goods_tag", "好油菜充值"); //商品标记 data.SetValue("notify_url", "http://www.yoursite.com/Checkout/ResultNotify"); //通知地址 data.SetValue("trade_type", "NATIVE"); //交易类型 data.SetValue("product_id", 121); //商品ID data.SetValue("sign", data.MakeSign()); //签名 //Logger.Info("获得签名" + data.GetValue("sign")); WxPayData result = WxPayApi.UnifiedOrder(data); //调用统一下单接口 //Logger.Info(result.ToJson()); string url = result.GetValue("code_url").ToString(); //获得统一下单接口返回的二维码链接 //Logger.Info("pay url:" + url); return(url); }
/// <summary> /// 获取审核结果 /// </summary> /// <param name="business_code"></param> /// <returns></returns> public static string Getstate(string business_code) { WxPayData inputObj = new WxPayData(); inputObj.SetValue("version", "1.0"); //接口版本号 inputObj.SetValue("mch_id", WxPayConfig.GetConfig().GetMchID()); //商户号 inputObj.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); //随机字符串 inputObj.SetValue("business_code", business_code); // inputObj.SetValue("sign_type", WxPayData.SIGN_TYPE_HMAC_SHA256); //签名类型 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); string url = "https://api.mch.weixin.qq.com/applyment/micro/getstate"; int timeOut = 10; Log.Debug("申请入驻", "request : " + xml); string response = HttpService.Post(xml, url, true, timeOut);//调用HTTP通信接口以提交数据到API Log.Debug("申请入驻", "response : " + response); return(response); }
/** * * 查询订单 * @param WxPayData inputObj 提交给查询订单API的参数 * @param int timeOut 超时时间 * @throws WxPayException * @return 成功时返回订单查询结果,其他抛异常 */ public static WxPayData OrderQuery(WxPayData inputObj, int timeOut = 6) { string url = "https://api.mch.weixin.qq.com/pay/orderquery"; //检测必填参数 if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id")) { throw new WxPayException("订单查询接口中,out_trade_no、transaction_id至少填一个!"); } inputObj.SetValue("appid", WxPayConfig.APPID); //公众账号ID inputObj.SetValue("mch_id", WxPayConfig.MCHID); //商户号 inputObj.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); //随机字符串 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); var start = DateTime.Now; Log.Debug("WxPayApi", "OrderQuery request : " + xml); string response = HttpService.Post(xml, url, false, timeOut); //调用HTTP通信接口提交数据 Log.Debug("WxPayApi", "OrderQuery response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds); //获得接口耗时 //将xml格式的数据转化为对象以返回 WxPayData result = new WxPayData(); result.FromXml(response); ReportCostTime(url, timeCost, result); //测速上报 return(result); }
public static addCard GetCardExt(Store store, string userCode) { LogHelper.WriteLog("GetCardExt start"); IUserStoreService userStoreService = new UserStoreService(); var cardId = ConfigurationManager.AppSettings["cardId"].ToString(); addCard addCard = new addCard(); addCard.cardId = cardId; CardExt cardExt = new CardExt(); LogHelper.WriteLog("store.appid:" + store.appid.Trim()); LogHelper.WriteLog("store.accessToken:" + store.accessToken); LogHelper.WriteLog("store.api_ticket:" + store.api_ticket); LogHelper.WriteLog("store.accessTokenCreateTime:" + store.accessTokenCreateTime); var userStore = userStoreService.GetUserStorebyUserCodestoreCode(userCode, store.StoreCode); if (!string.IsNullOrEmpty(store.accessToken) && !string.IsNullOrEmpty(store.api_ticket) && store.accessTokenCreateTime > DateTime.Now.AddHours(-1)) { var api_ticket = store.api_ticket; cardExt.code = WxPayApi.GenerateNonceStr(); cardExt.openid = userStore.OpenID; cardExt.nonce_str = WxPayApi.GenerateNonceStr(); cardExt.timestamp = WxPayApi.GenerateTimeStamp(); cardExt.signature = GetSignature(api_ticket, cardExt.nonce_str, cardExt.timestamp, cardExt.code, cardExt.openid, cardId); LogHelper.WriteLog("api_ticket :" + api_ticket); LogHelper.WriteLog("nonce_str :" + cardExt.nonce_str); LogHelper.WriteLog("timestamp :" + cardExt.timestamp); LogHelper.WriteLog("code :" + cardExt.code); LogHelper.WriteLog("openid :" + cardExt.openid); LogHelper.WriteLog("cardId :" + cardId); } else { var accessToken = wxAccessToken(store.appid.Trim(), store.secret.Trim()); if (accessToken != null) { if (!string.IsNullOrEmpty(accessToken.access_token)) { var wt = apiticket(accessToken.access_token); if (wt != null) { if (!string.IsNullOrEmpty(wt?.ticket)) { IStoreService _stoeservice = new StoreService(); store.accessToken = accessToken.access_token; store.api_ticket = wt?.ticket; store.accessTokenCreateTime = DateTime.Now; LogHelper.WriteLog("store.accessToken:" + store.accessToken); LogHelper.WriteLog("store.api_ticket:" + store.api_ticket); LogHelper.WriteLog("store.accessTokenCreateTime:" + store.accessTokenCreateTime); _stoeservice.UpdateStoreaccessToken(store); var api_ticket = store.api_ticket; cardExt.code = WxPayApi.GenerateNonceStr(); cardExt.openid = userStore.OpenID; cardExt.nonce_str = WxPayApi.GenerateNonceStr(); cardExt.timestamp = WxPayApi.GenerateTimeStamp(); cardExt.signature = GetSignature(api_ticket, cardExt.nonce_str, cardExt.timestamp, cardExt.code, cardExt.openid, ConfigurationManager.AppSettings["Company"].ToString()); LogHelper.WriteLog("api_ticket :" + api_ticket); LogHelper.WriteLog("nonce_str :" + cardExt.nonce_str); LogHelper.WriteLog("timestamp :" + cardExt.timestamp); LogHelper.WriteLog("code :" + cardExt.code); LogHelper.WriteLog("openid :" + cardExt.openid); LogHelper.WriteLog("cardId :" + cardId); } else { return(null); } } else { return(null); } } else { return(null); } } else { return(null); } } addCard.cardExt = cardExt; LogHelper.WriteLog("GetCardExt end"); return(addCard); }
public static WxConfig GetWxConfig(Store store, string url) { LogHelper.WriteLog("GetWxConfig start"); WxConfig wxConfig = new WxConfig(); LogHelper.WriteLog("store.appid:" + store.appid.Trim()); LogHelper.WriteLog("store.accessToken:" + store.accessToken); LogHelper.WriteLog("store.jsapi_ticket:" + store.jsapi_ticket); LogHelper.WriteLog("store.accessTokenCreateTime:" + store.accessTokenCreateTime); if (store.accessToken != null && store.jsapi_ticket != null && store.accessTokenCreateTime > DateTime.Now.AddHours(-1)) { url = url.Split('#')[0]; var jsapi_ticket = store.jsapi_ticket; wxConfig.appId = store.appid.Trim(); wxConfig.debug = true; wxConfig.nonceStr = WxPayApi.GenerateNonceStr(); wxConfig.timestamp = WxPayApi.GenerateTimeStamp(); wxConfig.jsApiList = new List <string>(); wxConfig.signature = signature(jsapi_ticket, wxConfig.nonceStr, wxConfig.timestamp, url); } else { var accessToken = wxAccessToken(store.appid.Trim(), store.secret.Trim()); if (accessToken != null) { if (!string.IsNullOrEmpty(accessToken.access_token)) { var wt = wxticket(accessToken.access_token); if (wt != null) { if (!string.IsNullOrEmpty(wt?.ticket)) { IStoreService _stoeservice = new StoreService(); store.accessToken = accessToken.access_token; store.jsapi_ticket = wt?.ticket; store.accessTokenCreateTime = DateTime.Now; LogHelper.WriteLog("store.accessToken:" + store.accessToken); LogHelper.WriteLog("store.jsapi_ticket:" + store.jsapi_ticket); LogHelper.WriteLog("store.accessTokenCreateTime:" + store.accessTokenCreateTime); var api_ticketwx = apiticket(accessToken.access_token); store.api_ticket = api_ticketwx?.ticket; LogHelper.WriteLog("store.api_ticket:" + store.api_ticket); _stoeservice.UpdateStoreaccessToken(store); url = url.Split('#')[0]; var jsapi_ticket = wt?.ticket; wxConfig.appId = store.appid.Trim(); wxConfig.debug = true; wxConfig.nonceStr = WxPayApi.GenerateNonceStr(); wxConfig.timestamp = WxPayApi.GenerateTimeStamp(); wxConfig.jsApiList = new List <string>(); wxConfig.signature = signature(jsapi_ticket, wxConfig.nonceStr, wxConfig.timestamp, url); } else { return(null); } } else { return(null); } } else { return(null); } } else { return(null); } } LogHelper.WriteLog("GetWxConfig end"); return(wxConfig); }
public static Dictionary <string, string> APPWxPayUnifiedorder(string trade_no, string body, string total_fee, bool IsOrder = true, bool IsChongZhi = false) { string url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; string wx_appid = PaymentConfig.WeiXinConfig.MobileAppID; string wx_mch_id = PaymentConfig.WeiXinConfig.MobileMCHID; string notify_url = string.Empty; if (IsChongZhi) { notify_url = WeixinConfig.app_chongzhi_notify_url; } else if (IsOrder) { notify_url = WeixinConfig.app_notify_url; } //统一下单 WxPayData data = new WxPayData(); data.SetValue("body", body); data.SetValue("attach", "test"); data.SetValue("out_trade_no", trade_no); data.SetValue("total_fee", total_fee); data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss")); data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss")); data.SetValue("goods_tag", "yongyouapp"); data.SetValue("trade_type", "APP"); data.SetValue("notify_url", notify_url); //异步通知url data.SetValue("appid", wx_appid); //公众账号ID data.SetValue("mch_id", wx_mch_id); //商户号 data.SetValue("spbill_create_ip", WxPayConfig.IP); //终端ip data.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); //随机字符串 data.SetValue("sign", data.MakeAPPSign()); string xml = data.ToXml(); string response = HttpService.Post(xml, url, false, 6); WxPayData result = new WxPayData(); result.FromXml(response); if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "") { throw new Exception("UnifiedOrder response error!"); } WxPayData appApiParam = new WxPayData(); appApiParam.SetValue("appid", wx_appid); appApiParam.SetValue("partnerid", wx_mch_id); appApiParam.SetValue("prepayid", result.GetValue("prepay_id")); appApiParam.SetValue("package", "Sign=WXPay"); appApiParam.SetValue("noncestr", WxPayApi.GenerateNonceStr()); appApiParam.SetValue("timestamp", WxPayApi.GenerateTimeStamp()); //appApiParam.SetValue("signType", "MD5"); appApiParam.SetValue("sign", appApiParam.MakeAPPSign()); //通信成功 var res = new Dictionary <string, string> { { "appid", appApiParam.GetValue("appid").ToString() }, { "partnerid", appApiParam.GetValue("partnerid").ToString() }, { "prepayid", appApiParam.GetValue("prepayid").ToString() }, { "package", appApiParam.GetValue("package").ToString() }, { "noncestr", appApiParam.GetValue("noncestr").ToString() }, { "timestamp", appApiParam.GetValue("timestamp").ToString() }, { "sign", appApiParam.GetValue("sign").ToString() } }; //在服务器上签名 return(res); }
public IActionResult AddOrdered(Order s) { var r = new RequestModel(); try { if (db.Orders.FirstOrDefault(c => c.Card == s.Card && c.ActiveId == s.ActiveId && s.Status == 1) != null) { r.code = 0; r.msg = "您已经报过名了"; return(Ok(r)); } var user = db.Users.Find(s.UserId); if (user == null) { r.code = 0; r.msg = "用户信息错误"; return(Ok(r)); } //新增 s.CreateTime = DateTime.Now; s.PayTime = DateTime.Now; s.Payno = WxPayAPI.WxPayApi.GenerateOutTradeNo(); s.Status = 0; //Active active = db.Actives.Find(s.ActiveId); Catory catory = db.Catorys.Find(s.ClassId); s.Grade = catory.Title; s.Money = catory.Price; s.PayMoney = 0.01M; if (s.Id > 0) { db.Orders.Update(s); } else { db.Orders.Add(s); } if (db.SaveChanges() > 0) { //Log.WriteLog("11111111:SUCCESS"); //生成与支付编号 unifiedOrderResult = GetUnifiedOrderResult(s.PayMoney, user.LoginName, s.Payno); //Log.WriteLog("11111111:222222222222222222"); WxPayData jsApiParam = new WxPayData(); jsApiParam.SetValue("appId", unifiedOrderResult.GetValue("appid")); jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp()); jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr()); jsApiParam.SetValue("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id")); jsApiParam.SetValue("signType", "MD5"); jsApiParam.SetValue("paySign", jsApiParam.MakeSign()); r.data = jsApiParam.ToJson(); r.code = 1; r.msg = s.Payno; } return(Ok(r)); } catch (Exception e) { //打印日志 r.msg = e.Message; } return(Ok(r)); }
public override void ProcessNotify(Action <NotifyModel> action) { WxPayData notifyData = GetNotifyData(); //检查openid和product_id是否返回 if (!notifyData.IsSet("openid") || !notifyData.IsSet("product_id")) { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "回调数据异常"); Log.Info(this.GetType().ToString(), "The data WeChat post is error : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } //调统一下单接口,获得下单结果 string openid = notifyData.GetValue("openid").ToString(); string product_id = notifyData.GetValue("product_id").ToString(); WxPayData unifiedOrderResult = new WxPayData(); try { unifiedOrderResult = UnifiedOrder(openid, product_id); } catch (Exception ex)//若在调统一下单接口时抛异常,立即返回结果给微信支付后台 { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "统一下单失败"); Log.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } //若下单失败,则立即返回结果给微信支付后台 if (!unifiedOrderResult.IsSet("appid") || !unifiedOrderResult.IsSet("mch_id") || !unifiedOrderResult.IsSet("prepay_id")) { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "统一下单失败"); Log.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } //统一下单成功,则返回成功结果给微信支付后台 WxPayData data = new WxPayData(); data.SetValue("return_code", "SUCCESS"); data.SetValue("return_msg", "OK"); data.SetValue("appid", WxPayConfig.APPID); data.SetValue("mch_id", WxPayConfig.MCHID); data.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); data.SetValue("prepay_id", unifiedOrderResult.GetValue("prepay_id")); data.SetValue("result_code", "SUCCESS"); data.SetValue("err_code_des", "OK"); data.SetValue("sign", data.MakeSign()); Log.Info(this.GetType().ToString(), "UnifiedOrder success , send data to WeChat : " + data.ToXml()); page.Response.Write(data.ToXml()); page.Response.End(); }
protected void Page_Load(object sender, EventArgs e) { string outString = ""; string yqStr = ""; string qst = ""; string phoneno = ""; bool isallok = false; double LoginMaxSecond = 120; double TotalSeconds = 0; string LoginMD5_key = ""; DateTime ddd = new DateTime(); bool wxdebug = false; EGO_Order_List order; OrderEgoBLL orderBLL = new OrderEgoBLL(); string orderno = ""; string fileName = ""; Json_Response_Base.UploadPic_resultPackage jrb = new Json_Response_Base.UploadPic_resultPackage(); if (!bool.TryParse(Request["debug"] ?? "", out wxdebug)) { wxdebug = false; } try { ResultPacket rp = new ResultPacket(); Json_Response_Base.resultPackage jrp = new Json_Response_Base.resultPackage(); switch (Request["action"]) { //收货地址验证码 case "addressvalidcode": rp = SMSBll.MakeSMSCodeAndSend(Request["mobileno"], JYH_SMSCode.EnumSMSTradeType.SaveAddress); jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); break; //收货地址验证码 case "loginvalidcode": rp = SMSBll.MakeSMSCodeAndSend(Request["mobileno"], (int)JYH_SMSCode.EnumSMSTradeType.PhoneLogin, Request["piccode"]); jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); break; //收货地址验证码 case "oauthvalidcode": rp = SMSBll.MakeSMSCodeAndSend(Request["mobileno"], JYH_SMSCode.EnumSMSTradeType.BindMobileAndMobileReg); jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); break; //手机注册验证码 case "registervalidcode": rp = SMSBll.MakeSMSCodeAndSend(Request["mobileno"], (int)JYH_SMSCode.EnumSMSTradeType.PhoneRegister, Request["piccode"]); jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); break; //重新设置密码 case "passwordreset": phoneno = Session["UserName"] == null ? (Request["phoneno"] ?? "") : Session["UserName"].ToString(); jrp = new LoginBLL().ResetPassWord(phoneno, Request["validcode"], Request["password"]); outString = JsonHelper.ToJsonString(jrp); break; //重置密码验证码 case "resetpasswordvalidcode": phoneno = Session["UserName"] == null ? (Request["mobileno"] ?? "") : Session["UserName"].ToString(); rp = SMSBll.MakeSMSCodeAndSend(phoneno, (int)JYH_SMSCode.EnumSMSTradeType.PasswordReset, Request["piccode"]); jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); break; //手机注册验证码 case "lqfxtqvalidcode": rp = SMSBll.MakeSMSCodeAndSend(Request["mobileno"], (int)JYH_SMSCode.EnumSMSTradeType.LQFXTQ, Request["piccode"]); jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); break; //用户登录 case "userlogin": try { jrp = new LoginBLL().CheckLogin(Request["username"], Request["password"]); outString = JsonHelper.ToJsonString(jrp); if (jrp.resultcode == "1") { try { //保存用户信息至本地 new LoginBLL().SyncJYHMemberInfo(Request["password"], "wap"); } catch (Exception exd) { //记录异常 ProjectLogBLL.NotifyProjectLog(string.Format("一元购-保存用户信息至本地--异常:{0}", exd.ToString()), "active:API.asp的" + Request["action"]); } } } catch (Exception ex) { jrp.resultcode = "98"; jrp.resultmessage = ex.ToString(); outString = JsonHelper.ToJsonString(jrp); } break; //手机登录 case "phonelogin": jrp = new LoginBLL().CheckPhoneLogin(Request["phoneno"], Request["validcode"]); if (jrp.resultcode == "1") { try { //保存用户信息至本地 new LoginBLL().SyncJYHMemberInfo("", "wap"); } catch (Exception exd) { //记录异常 ProjectLogBLL.NotifyProjectLog(string.Format("一元购-保存用户信息至本地--异常:{0}", exd.ToString()), "active:API.asp的" + Request["action"]); } } outString = JsonHelper.ToJsonString(jrp); break; //只使用手机号直接登录,from=web的需要验签,安卓和ios直接登录 case "phoneloginauto": if (Request["type"] == "web") { try { //测试 //jrp = new LoginBLL().CheckPhoneLoginApp(Request["phoneno"]); //outString = JsonHelper.ToJsonString(jrp); //验签 if (Request["phoneno"] != null && Request["tt"] != null && Request["mac"] != null) { //判断时间是否自有效期内 LoginMaxSecond = INITools.GetIniKeyValue("autologinurl", "LoginMaxSecond") == "" ? 0 : double.Parse(INITools.GetIniKeyValue("autologinurl", "LoginMaxSecond")); // ConfigurationManager.AppSettings["LoginMaxSecond"] == null ? 120 : double.Parse(ConfigurationManager.AppSettings["LoginMaxSecond"].ToString()); qst = Request["tt"]; if (qst == "") { jrp.resultcode = "99"; jrp.resultmessage = "缺少参数"; } else { TimeSpan ts = DateTime.Now - DateTime.Parse("1970-1-1"); TotalSeconds = ts.TotalSeconds; TotalSeconds = TotalSeconds - double.Parse(qst); if (TotalSeconds >= LoginMaxSecond || TotalSeconds < 0) { jrp.resultcode = "99"; jrp.resultmessage = "已失效"; } else { LoginMD5_key = INITools.GetIniKeyValue("autologinurl", "LoginMD5_key") == "" ? "" : INITools.GetIniKeyValue("autologinurl", "LoginMD5_key"); yqStr = Request["phoneno"] + qst + LoginMD5_key; //验签通过 if (DESHelper.Md5(yqStr) == Request["mac"].ToString()) { //判断是否有手机号 if (Request["phoneno"] != "") { } else { jrp.resultcode = "99"; jrp.resultmessage = "缺少手机号"; } } else { jrp.resultcode = "99"; jrp.resultmessage = "签名错误"; } } } } else { jrp.resultcode = "99"; jrp.resultmessage = "缺少参数"; } } catch (Exception edf) { jrp.resultcode = "99"; jrp.resultmessage = "程序异常"; } if (jrp.resultcode != "99") { //登录 jrp = new LoginBLL().CheckPhoneLoginApp(Request["phoneno"]); if (jrp.resultcode == "1") { try { //保存用户信息至本地 new LoginBLL().SyncJYHMemberInfo("", "wap"); } catch (Exception exd) { //记录异常 ProjectLogBLL.NotifyProjectLog(string.Format("一元购-保存用户信息至本地--web登录--异常:{0}", exd.ToString()), "active:API.asp的" + Request["action"]); } } outString = JsonHelper.ToJsonString(jrp); } else { //用户注销 try { new LoginBLL().UserLoginOut(); } catch (Exception sse) { } } } else { jrp = new LoginBLL().CheckPhoneLoginApp(Request["phoneno"]); if (jrp.resultcode == "1") { try { //保存用户信息至本地 new LoginBLL().SyncJYHMemberInfo("", "wap"); } catch (Exception exd) { //记录异常 ProjectLogBLL.NotifyProjectLog(string.Format("一元购-保存用户信息至本地--APP登录--异常:{0}", exd.ToString()), "active:API.asp的" + Request["action"]); } } } outString = JsonHelper.ToJsonString(jrp); break; //用户注销 case "userlogout": jrp = new LoginBLL().UserLoginOut(); outString = JsonHelper.ToJsonString(jrp); break; //手机注册 case "phonereg": jrp = new LoginBLL().CheckPhoneReg(Request["phoneno"], Request["validcode"], Request["password"]); outString = JsonHelper.ToJsonString(jrp); break; case "phonereg_lqfxtq": jrp = new LoginBLL().CheckPhoneReg(Request["phoneno"], Request["validcode"], Request["password"], JYH_SMSCode.EnumSMSTradeType.LQFXTQ, Request["sharephone"]); outString = JsonHelper.ToJsonString(jrp); break; //检测是否登录 case "checklogin": jrp = new LoginBLL().CheckLoginSession(); outString = JsonHelper.ToJsonString(jrp); break; //手机登录 case "phoneexist": if (LoginBLL.CheckPhoneExist(Request["phoneno"])) { jrp.resultcode = "99"; jrp.resultmessage = "已存在"; } else { jrp.resultcode = "1"; jrp.resultmessage = "不存在"; } outString = JsonHelper.ToJsonString(jrp); break; //获取地址列表 case "addresslist": string addressList = ""; rp = new OrderBLL().GetAddressList(out addressList); if (rp.IsError) { jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); } else { outString = addressList; } break; //新增收货地址 case "addressadd": rp = new OrderBLL().AddAddressForOrder(Request["api_input"], Request["validcode"]); jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); break; //修改收货地址 case "addressedit": rp = new OrderBLL().EditAddressForOrder(Request["api_input"], Request["validcode"]); jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); break; //根据id获得地址 case "getaddressbyid": string addressByID = ""; rp = new OrderBLL().GetAddressByID(Request["addressid"], out addressByID); if (rp.IsError) { jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); } else { outString = addressByID; if (outString == "") { jrp.resultcode = "1000"; jrp.resultmessage = "收货地址已删除,请重新设置收货地址"; outString = JsonHelper.ToJsonString(jrp); } } break; //获取默认收货地址 case "addressdefault": string addressDetail = ""; rp = new OrderBLL().GetAddressDefault(out addressDetail); if (rp.IsError) { jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); } else { outString = addressDetail; if (outString == "") { jrp.resultcode = "1000"; jrp.resultmessage = "收货地址已删除,请重新设置收货地址"; outString = JsonHelper.ToJsonString(jrp); } } break; case "merchant_check": Merchant_PageBLL checkBll = new Merchant_PageBLL(); foreach (string key in Request.Form.Keys) { checkBll._paramList.Add(key, HttpUtility.UrlDecode(Request.Form[key])); } string from = Request["merchantcode"].ToString(); if (!string.IsNullOrEmpty(from)) { outString = checkBll.NotifyMerchantApiData(); if (outString == "-1") { from = ""; } else { if (JsonHelper.JsonToObject <Json_Response_Base.resultPackage>(outString).resultcode != "1") { from = ""; } } } checkBll.CheckMerchantValid(Request["host"].ToString(), Request["refer"].ToString(), from); if (Session["MerchantID_HJY"] != null) { jrp.resultcode = "1"; jrp.resultmessage = from; } else { jrp.resultcode = "99"; jrp.resultmessage = "已失效"; } outString = JsonHelper.ToJsonString(jrp); break; //获取拼团信息 case "getpininfo": string pinInfo = ""; rp = new PinBLL().GetPinListByEventCode(Request["eid"].ToString(), out pinInfo); if (rp.IsError) { jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); } else { outString = pinInfo; } break; //获取我的团信息 case "mytuans": string myTuans = ""; rp = new PinBLL().GetMyTuans(out myTuans); if (rp.IsError) { jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); } else { outString = myTuans; } break; //获取我的订单 case "myorders": string myOrders = ""; rp = new PinBLL().GetMyOrders(out myOrders); if (rp.IsError) { jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); } else { outString = myOrders; } break; //获取我的订单详情 case "myorderdetail": string myOrderDetail = ""; rp = new PinBLL().GetMyOrderDetail(Request.Form["oid"], out myOrderDetail); if (rp.IsError) { jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); } else { outString = myOrderDetail; } break; //获取活动订单 case "eventorders": string eventOrders = ""; rp = new PinBLL().GetEventOrdersByEventCode(Request.Form["eid"], out eventOrders); if (rp.IsError) { jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); } else { outString = eventOrders; } break; //参加拼团 case "pin": var num = int.Parse(Request.Form["num"]); var endTime = DateTime.Parse(Request.Form["endTime"].ToString()); rp = new PinBLL().Pin(num, endTime, Request.Form["json"].ToString()); jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); break; //监测是否可以参加拼团 case "iscanpin": rp = new PinBLL().IsCanPin(int.Parse(Request.Form["Num"].ToString()), DateTime.Parse(Request.Form["endTime"].ToString()), Request.Form["eventCode"].ToString()); jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); break; //更新拼团状态 case "updatetuanstatus": rp = new PinBLL().UpdatePinTuanStatus(Request.Form["eventCode"].ToString(), (JYH_Pin_List.EnumTuanStatus)(int.Parse(Request.Form["status"]))); jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); break; //更新支付状态 case "updatepaystatus": rp = new PinBLL().UpdatePayStatus(Request.Form["order_code"].ToString(), (JYH_Pin_Detail.EnumPayStatus)(int.Parse(Request.Form["status"]))); jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); break; case "wxpay": //不经过支付网关 try { JsApiPay jsApiPay = new JsApiPay(this); jsApiPay.openid = Session["wxPayOpenid"].ToString(); //"oz1WBs_FPv5qbh1cyyoN9fzNZgUw"; jsApiPay.total_fee = (int)(decimal.Parse(Request["total_fee"].ToString()) * 100); jsApiPay.orderid = Request["orderid"]; WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(); outString = jsApiPay.GetJsApiParameters(); FileHelper.WriteLogFile(Server.MapPath("log"), "wxOpenid", jsApiPay.openid); } catch (Exception ex) { FileHelper.WriteLogFile(Server.MapPath("log"), "wxOpenid", ex.ToString()); } break; case "test": rp = new PinBLL().Request_ApiBySendList(0, 0); jrp.resultcode = rp.ResultCode; jrp.resultmessage = rp.Description; outString = JsonHelper.ToJsonString(jrp); break; ///*创建订单*/ //case "createorder": // order = new EGO_Order_List(); // order.ProductID = int.Parse(Request["ProductID"]); // order.PeriodNum = int.Parse(Request["PeriodNum"]); // order.OrderNo = RunProcedure.Exec_CreateSerialNo(10001); // order.OrderTime = DateTime.Now; // order.BuyerPhone = HttpContext.Current.Session["UserName"].ToString(); // order.ChipinNum =int.Parse(Request["ChipinNum"]);; // order.Status =EGO_Order_List.EnumOrderStatus.Init; // order.TotalMoney =decimal.Parse(Request["TotalMoney"]); // order.PayGate =(EnumPaygate)int.Parse(Request["PayGate"]); // order.PayGateType =(EnumPaygateType)int.Parse(Request["PayGateType"]); // if (orderBLL.Insert(order)) // { // outString = order.OrderNo; // } // else { // outString = ""; // } // break; ///*使用支付网关支付*/ //case "gotopayment": // //取得支付网关的参数 // orderno = Request["OrderNo"] ?? ""; // order = OrderBLL.GetOrderInfo(orderno); // if (order.PayGate == EnumPaygate.WeiXin_JSAPI) // { // //微信JSAPI // if (order.OpenID != "") // { // order.OpenID = Session["wxPayOpenid"].ToString(); // outString = PaygateBLL.GoToPayMent(order); // } // else { // outString = ""; // } // } // else // { // //支付宝 // outString = PaygateBLL.GoToPayMent(order); // } // break; case "wxshare": //微信内JSAPI分享 WX_JSAPI_Config jaapiconfig = new WX_JSAPI_Config(); jaapiconfig.resultcode = "0"; jaapiconfig.resultmessage = "操作成功"; string jsApiList = Request["jsApiList"] ?? ""; string url = Request["surl"] ?? ""; if (jsApiList == "") { jaapiconfig.resultcode = "1"; jaapiconfig.resultmessage = "要调用的接口不能为空"; } else if (url == "") { jaapiconfig.resultcode = "2"; jaapiconfig.resultmessage = "当前页面的url不能为空"; } else { WX_JSAPI_Ticket_Response ticket = WxJsApiData.GetJsApiTicket("jsapi"); if (ticket == null) { jaapiconfig.resultcode = "3"; jaapiconfig.resultmessage = "获取ticket失败."; } else { jaapiconfig.appId = WxPayConfig.APPID; jaapiconfig.debug = wxdebug; jaapiconfig.jsApiList = jsApiList.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); jaapiconfig.nonceStr = WxPayApi.GenerateNonceStr(); jaapiconfig.timestamp = WxPayApi.GenerateTimeStamp(); jaapiconfig.ticket = ticket.ticket; jaapiconfig.url = url; jaapiconfig.signature = WxJsApiData.getSign(jaapiconfig); } } outString = JsonHelper.ToJsonString(jaapiconfig); break; #region 图片* /*上传图片*/ case "uploadimg": //====使用服务器物理路径,可实现上传======================================== //获取图片控件 string file_ID = Request["fileid"]; //.Split('|'); //string return_img_path = ""; var file = Request.Files[file_ID]; //var file =Request.Files[0]; //上传图片文件路径【通过虚拟目录获得对应的物理地址,虚拟目录地址需指向文件服务器的共享路径】 string temp_filePath = ConfigurationManager.AppSettings["UploadIMG"]; //图片上传物理路径(当前服务器上) string filePath = new System.Web.UI.Page().Server.MapPath(temp_filePath); ////图片上传物理路径(相对于文件服务器的地址) //string filePath = ConfigurationManager.AppSettings["UploadIMG"]; int maxSize = 0; string path = ""; if (file == null) { outString = "{\"resultCode\":\"1\",\"resultMessage\":\"请上传图片信息!\"}"; } fileName = file.FileName; string aaa = Encoding.UTF8.GetString(Encoding.Default.GetBytes(file.FileName)); string exName = ""; if (Path.GetExtension(aaa) == "") { exName = fileName.Substring(fileName.LastIndexOf('?')).Replace("?", "."); } else { exName = fileName.Substring(fileName.LastIndexOf('.')); } if (exName == "") { exName = "." + fileName.Substring(fileName.Length - 3, 3); } //重命名 //int seed = Guid.NewGuid().GetHashCode(); //var random = new System.Random(seed); string newFileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + "" + RandHelper.Next(100000, 999999); if (Directory.Exists(filePath) == false) { Directory.CreateDirectory(filePath); } path = filePath + "\\" + newFileName + exName; file.SaveAs(path); //图片访问路径 string baseurl = ""; if (Request["saveFullPath"] != null) { baseurl = ConfigurationManager.AppSettings["UploadIMG_YM"]; //Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port; } jrb.resultmessage = baseurl + ConfigurationManager.AppSettings["UploadIMG_Path"] + newFileName + exName; jrb.resultcode = "1"; outString = JsonHelper.ToJsonString(jrb); break; #endregion case "group_back": if (Session["group_back"] != null) { jrp.resultcode = "1"; jrp.resultmessage = "正常"; } else { jrp.resultcode = "99"; jrp.resultmessage = "已失效"; } outString = JsonHelper.ToJsonString(jrp); break; case "merchant_page": if (Session["MerchantID_HJY"] != null || (!string.IsNullOrEmpty(Request["recordact"]))) { Merchant_PageBLL pageBll = new Merchant_PageBLL(); foreach (string key in Request.Form.Keys) { pageBll._paramList.Add(key, HttpUtility.UrlDecode(Request.Form[key])); } outString = pageBll.NotifyMerchantApiData(); if (outString == "-1") { jrp.resultcode = "99"; jrp.resultmessage = "通知失败"; outString = JsonHelper.ToJsonString(jrp); } } else { if (Request["recordact"].ToString() != "") { } jrp.resultcode = "98"; jrp.resultmessage = "已失效"; outString = JsonHelper.ToJsonString(jrp); } break; } } catch (Exception ex) { ProjectLogBLL.NotifyProjectLog(string.Format("异常:{0}", ex.ToString()), "api-" + Request["action"]); } Response.Write(outString); }
private string OnPay(DataRow row) { #region 获取基本参数 string CommunityId = string.Empty; if (row.Table.Columns.Contains("CommunityId")) { CommunityId = row["CommunityId"].ToString(); } string RoomID = string.Empty; if (row.Table.Columns.Contains("RoomID")) { RoomID = row["RoomID"].ToString(); } string CustID = string.Empty; if (row.Table.Columns.Contains("CustID")) { CustID = row["CustID"].ToString(); } string OpenID = string.Empty; if (row.Table.Columns.Contains("OpenID")) { OpenID = row["OpenID"].ToString(); } if (!row.Table.Columns.Contains("PayChannel") || string.IsNullOrEmpty(row["PayChannel"].ToString())) { return(new ApiResult(false, "参数PayChannel有误").toJson()); } var community = GetCommunity(CommunityId); if (community == null) { return(JSONHelper.FromString(false, "未查询到小区信息")); } int CommID = AppGlobal.StrToInt(community.CommID); PubConstant.hmWyglConnectionString = GetConnectionStr(community); var payChannel = row["PayChannel"].ToString(); var payType = 0; switch (payChannel.ToLower()) { case PayChannelString.Alipay: payType = 1; break; case PayChannelString.WechatPay: payType = 2; break; case PayChannelString.AllInPay_Alipay: payType = 1; break; case PayChannelString.AllInPay_WechatPay: payType = 2; break; default: return(new ApiResult(false, "参数payChannel有误").toJson()); } if (payType == 2) { if (payChannel.ToLower().Equals(PayChannelString.AllInPay_WechatPay) && string.IsNullOrEmpty(OpenID)) { return(new ApiResult(false, "参数OpenID不能为空").toJson()); } } #endregion using (IDbConnection erpConn = new SqlConnection(PubConstant.hmWyglConnectionString)) { dynamic tb_Payment_Config = erpConn.QueryFirstOrDefault <dynamic>("SELECT * FROM Tb_Payment_Config WITH(NOLOCK) WHERE CommID = @CommID", new { CommID }); if (null == tb_Payment_Config) { return(new ApiResult(false, "该项目未开通对应支付方式").toJson()); } // 旧方式获取对应支付配置 AllinConfig allinConfig = null; // 新方式获取支付配置 PaymentConfig paymentConfig = null; if (payChannel == PayChannelString.AllInPay_Alipay || payChannel == PayChannelString.AllInPay_WechatPay) { try { allinConfig = JsonConvert.DeserializeObject <AllinConfig>(tb_Payment_Config.Config); if (null == allinConfig) { return(new ApiResult(false, "该项目支付类型对应配置有误").toJson()); } } catch (Exception) { return(new ApiResult(false, "该项目支付类型对应配置有误").toJson()); } } else { // 新的方式,Config存储多个配置 try { // ERP的配置表,要求存储一个Json数组,用于配置支持不同支付方式 // 配置项要求存储一个 List <PaymentConfig> configs = JsonConvert.DeserializeObject <List <PaymentConfig> >(tb_Payment_Config.Config); if (null == configs || configs.Count <= 0) { return(new ApiResult(false, "该项目支付类型对应配置有误").toJson()); } if (payChannel == PayChannelString.Alipay) { paymentConfig = configs.Find(item => item.type == "AliPay"); } if (payChannel == PayChannelString.WechatPay) { paymentConfig = configs.Find(item => item.type == "WChatPay"); } if (null == paymentConfig) { return(new ApiResult(false, "该项目支付类型对应配置有误").toJson()); } } catch (Exception) { } } #region 计算金额 if (!row.Table.Columns.Contains("PayData") || string.IsNullOrEmpty(row["PayData"].ToString())) { return(new ApiResult(false, "缺少参数PayData").toJson()); } string PayData = row["PayData"].ToString(); if (!CheckPayData(Global_Fun.BurstConnectionString(CommID, Global_Fun.BURST_TYPE_CHARGE), Convert.ToInt64(CustID), Convert.ToInt64(RoomID), PayData, out decimal Amt, out string errMsg, true, false, !"1940".Equals(Global_Var.LoginCorpID))) { return(new ApiResult(false, errMsg).toJson()); } if (Amt <= 0.00M) { return(new ApiResult(false, "金额必须大于0").toJson()); } #endregion JObject PayDataObj = JObject.Parse(PayData); int Type = (int)PayDataObj["Type"]; #region 查询项目名称和房屋编号,拼接费用备注 string FeesMemo = string.Empty; string RoomSign = string.Empty; if (Type == 1) { FeesMemo = "物业综合费用缴纳"; string CommName = erpConn.QueryFirstOrDefault <string>("SELECT CommName FROM Tb_HSPR_Community WHERE CommID = @CommID", new { CommID }); if (string.IsNullOrEmpty(CommName)) { CommName = Convert.ToString(CommID); } RoomSign = erpConn.QueryFirstOrDefault <string>("SELECT ISNULL(RoomSign,RoomName) AS RoomSign FROM Tb_HSPR_Room WHERE RoomID = @RoomID", new { RoomID }); if (string.IsNullOrEmpty(RoomSign)) { RoomSign = Convert.ToString(RoomID); } FeesMemo += string.Format("-{0}-{1}", CommName, RoomSign); } else { FeesMemo = "物业综合费用预存"; string CommName = erpConn.QueryFirstOrDefault <string>("SELECT CommName FROM Tb_HSPR_Community WHERE CommID = @CommID", new { CommID }); if (string.IsNullOrEmpty(CommName)) { CommName = Convert.ToString(CommID); } RoomSign = erpConn.QueryFirstOrDefault <string>("SELECT ISNULL(RoomSign,RoomName) AS RoomSign FROM Tb_HSPR_Room WHERE RoomID = @RoomID", new { RoomID }); if (string.IsNullOrEmpty(RoomSign)) { RoomSign = Convert.ToString(RoomID); } FeesMemo += string.Format("-{0}-{1}", CommName, RoomSign); } #endregion string NoticeId = Guid.NewGuid().ToString(); // 生成订单 if (erpConn.Execute("INSERT INTO Tb_Notice(Id, CommID, RoomID, CustID, PayData, CreateTime) VALUES(@Id, @CommID, @RoomID, @CustID, @PayData, @CreateTime)", new { Id = NoticeId, CommID, RoomID, CustID, PayData, CreateTime = DateTime.Now.ToString() }) <= 0) { return(new ApiResult(false, "创建收款订单失败,请重试").toJson()); } string ChargeMode = "业主APP缴费"; if (payChannel == PayChannelString.AllInPay_Alipay) { ChargeMode = "通联_业主APP(支付宝)"; } else if (payChannel == PayChannelString.AllInPay_WechatPay) { ChargeMode = "通联_业主APP(微信)"; } else { ChargeMode = "通联_业主APP"; } #region 修改收款方式 if (erpConn.QueryFirstOrDefault <int>("SELECT COUNT(1) FROM syscolumns WHERE id=object_id('Tb_Notice') AND name = 'ChargeMode'") > 0) { erpConn.Execute("UPDATE Tb_Notice SET ChargeMode = @ChargeMode WHERE Id = @Id", new { ChargeMode, Id = NoticeId }); } #endregion DateTime dateNow = DateTime.Now; string OrderSN = dateNow.ToString("yyyyMMddHHmmssfff") + Utils.BuildRandomStr(3); string PaymentNotifyUrl = string.Empty; Dictionary <string, string> param = null; if (payChannel == PayChannelString.AllInPay_Alipay || payChannel == PayChannelString.AllInPay_WechatPay) { #region 请求通联支付 #region 获取对应类型的下账地址 if (Type == 1) { PaymentNotifyUrl = AppGlobal.GetAppSetting("AllinPay_Notify_Url") + "?CommID=" + CommID; } else { PaymentNotifyUrl = AppGlobal.GetAppSetting("AllinPay_Prec_Notify_Url") + "?CommID=" + CommID; } #endregion try { param = SybWxPayService.Pay(Convert.ToInt64(Amt * 100), OrderSN, payChannel == PayChannelString.AllInPay_Alipay ? "A01" : "W06", FeesMemo, RoomSign, OpenID, "", PaymentNotifyUrl, "", "", "", "", allinConfig.orgid, allinConfig.appid, allinConfig.custid, allinConfig.appkey, allinConfig.subbranch); if (param == null || !param.ContainsKey("payinfo")) { GetLog().Error("OnPay:" + JsonConvert.SerializeObject(param)); return(new ApiResult(false, "生成支付订单失败,请重试").toJson()); } } catch (Exception ex) { GetLog().Error("OnPay", ex); return(new ApiResult(false, "生成支付订单失败,请重试").toJson()); } if (erpConn.Execute(@"INSERT INTO Tb_Payment_Order(PayType, OrderSN, NoticeId, Amt, CreateTime) VALUES(@PayType, @OrderSN, @NoticeId, @Amt, @CreateTime)", new { PayType = payType, OrderSN = OrderSN, NoticeId = NoticeId, Amt = Amt, CreateTime = dateNow }) <= 0) { return(new ApiResult(false, "生成支付订单失败,请重试(1003)").toJson()); } return(new ApiResult(true, new { OrderSN = OrderSN, QrCode = param["payinfo"].ToString() }).toJson()); #endregion } if (payChannel == PayChannelString.Alipay) { AliConfig aliConfig = null; try { aliConfig = Config.GetConfig <AliConfig>(paymentConfig.config); if (null == aliConfig) { return(new ApiResult(false, "该项目支付类型对应配置有误").toJson()); } } catch (Exception) { return(new ApiResult(false, "该项目支付类型对应配置有误").toJson()); } #region 请求支付宝官方支付 #region 获取对应类型的下账地址 PaymentNotifyUrl = AppGlobal.GetAppSetting("AliPay_Notify_Url"); #endregion AlipayTradeAppPayResponse response = null; try { JObject BizContent = new JObject(); //要求15分钟内支付 BizContent.Add("timeout_express", "15m"); BizContent.Add("total_amount", Amt); BizContent.Add("body", FeesMemo); BizContent.Add("subject", FeesMemo); BizContent.Add("out_trade_no", OrderSN); IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", aliConfig.appid, aliConfig.app_private_key, "json", "1.0", "RSA2", aliConfig.alipay_public_key, "UTF-8", false); AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest { BizContent = JsonConvert.SerializeObject(BizContent), }; request.SetNotifyUrl(PaymentNotifyUrl); response = client.SdkExecute(request); } catch (Exception ex) { Log(ex.Message, "AliPayLogs\\"); GetLog().Error(ex.Message + Environment.CommandLine + ex.StackTrace); return(new ApiResult(false, "请求订单失败,请重试").toJson()); } if (erpConn.Execute("INSERT INTO Tb_Payment_Order(PayType, OrderSN, NoticeId, Amt, CreateTime) VALUES(@PayType, @OrderSN, @NoticeId, @Amt, @CreateTime)", new { PayType = 1, OrderSN, NoticeId = NoticeId, Amt = Amt, CreateTime = dateNow }) <= 0) { return(new ApiResult(false, "生成订单失败").toJson()); } return(new ApiResult(true, new { OrderSN = OrderSN, QrCode = response.Body }).toJson()); #endregion } if (payChannel == PayChannelString.WechatPay) { WxConfig wxConfig = null; try { wxConfig = Config.GetConfig <WxConfig>(paymentConfig.config); if (null == wxConfig) { return(new ApiResult(false, "该项目支付类型对应配置有误").toJson()); } } catch (Exception) { return(new ApiResult(false, "该项目支付类型对应配置有误").toJson()); } #region 请求微信官方支付 #region 获取对应类型的下账地址 PaymentNotifyUrl = AppGlobal.GetAppSetting("WxPay_Notify_Url"); #endregion WxPayData wxPayData = new WxPayData(); wxPayData.SetValue("appid", wxConfig.appid); wxPayData.SetValue("body", FeesMemo); wxPayData.SetValue("mch_id", wxConfig.mch_id); wxPayData.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); wxPayData.SetValue("notify_url", PaymentNotifyUrl); wxPayData.SetValue("out_trade_no", OrderSN); wxPayData.SetValue("spbill_create_ip", "8.8.8.8"); wxPayData.SetValue("total_fee", Convert.ToInt32(Amt * 100)); wxPayData.SetValue("trade_type", "APP"); wxPayData.SetValue("sign_type", wxpay.utils.WxPayData.SIGN_TYPE_HMAC_SHA256); wxPayData.SetValue("sign", wxPayData.MakeSign(wxConfig.appkey)); try { wxPayData = WxPayApi.UnifiedOrder(wxPayData); } catch (Exception) { return(new ApiResult(false, "请求超时,请重试").toJson()); } if (!wxPayData.IsSet("return_code") || !"SUCCESS".Equals(wxPayData.GetValue("return_code").ToString())) { return(new ApiResult(false, "请求支付订单失败").toJson()); } if (!wxPayData.IsSet("result_code") || !"SUCCESS".Equals(wxPayData.GetValue("result_code").ToString())) { return(new ApiResult(false, "请求支付订单失败").toJson()); } if (!wxPayData.IsSet("prepay_id")) { return(new ApiResult(false, "请求支付订单失败").toJson()); } string prepay_id = wxPayData.GetValue("prepay_id").ToString(); if (erpConn.Execute("INSERT INTO Tb_Payment_Order(PayType, OrderSN, NoticeId, Amt, CreateTime) VALUES(@PayType, @OrderSN, @NoticeId, @Amt, @CreateTime)", new { PayType = 2, OrderSN, NoticeId = NoticeId, Amt = Amt, CreateTime = dateNow }) <= 0) { return(new ApiResult(false, "生成订单失败").toJson()); } WxPayData result = new WxPayData(); result.SetValue("appid", wxPayData.GetValue("appid").ToString()); result.SetValue("partnerid", wxPayData.GetValue("mch_id").ToString()); result.SetValue("prepayid", prepay_id); result.SetValue("package", "Sign=WXPay"); result.SetValue("noncestr", wxPayData.GetValue("nonce_str").ToString()); result.SetValue("timestamp", WxPayApi.GenerateTimeStamp()); result.SetValue("sign", result.MakeSign(wxpay.utils.WxPayData.SIGN_TYPE_HMAC_SHA256, wxConfig.appkey)); JObject jObj = JObject.Parse(result.ToJson()); return(new ApiResult(true, new { OrderSN = OrderSN, QrCode = jObj }).toJson()); #endregion } return(new ApiResult(false, "不支持的支付方式").toJson()); } }
public static string getcardExtcode(string phone) { return(WxPayApi.GenerateNonceStr() + phone); }
public string GenerateNonceStr() { return(WxPayApi.GenerateNonceStr()); }
/// <summary> /// 微信支付通道安卓调用方式 /// </summary> /// <param name="appid">应用id</param> /// <param name="code">订单编号</param> /// <param name="goodsname">商品名称</param> /// <param name="price">商品价格</param> /// <param name="orderid">订单id</param> /// <param name="apptype">风控配置表id</param> /// <returns></returns> private InnerResponse PayWxAz(int appid, string code, string goodsname, decimal price, int orderid, string ip, int apptype, int infoTimes) { InnerResponse inn = new InnerResponse(); SelectInterface SeIn = new SelectInterface(); try { string wxappidzfjk = "wxappidzfjk" + appid;//组装缓存key值 SeIn = SelectUserInfo(wxappidzfjk, appid, apptype, infoTimes); if (SeIn == null || SeIn.PayId <= 0) { inn = inn.ToResponse(ErrorCode.Code106); return(inn); } if (SeIn.PayId > 0) { WxPayConfig wx = new WxPayConfig(SeIn.PayId); JMP.BLL.jmp_order bll = new JMP.BLL.jmp_order(); if (!UpdateOrde.OrdeUpdateInfo(orderid, SeIn.PayId)) { inn = inn.ToResponse(ErrorCode.Code101); return(inn); } if (!JudgeMoney.JudgeMinimum(price, SeIn.minmun)) { inn = inn.ToResponse(ErrorCode.Code8990); return(inn); } if (!JudgeMoney.JudgeMaximum(price, SeIn.maximum)) { inn = inn.ToResponse(ErrorCode.Code8989); return(inn); } WxPayData data = new WxPayData(); data.SetValue("body", goodsname); //商品名称 data.SetValue("out_trade_no", code); //我们的订单号 data.SetValue("total_fee", (Convert.ToInt32(price * 100)).ToString()); //价格 data.SetValue("notify_url", ConfigurationManager.AppSettings["WxTokenUrl"].ToString().Replace("{0}", SeIn.PayId.ToString())); //回调地址 data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss")); data.SetValue("time_expire", DateTime.Now.AddMinutes(30).ToString("yyyyMMddHHmmss")); data.SetValue("trade_type", "APP"); WxPayData result = WxPayApi.UnifiedOrder(data, SeIn.PayId); string noncestr = WxPayApi.GenerateNonceStr(); string timestamp = WxPayApi.GenerateTimeStamp(); WxPayData data1 = new WxPayData(); data1.SetValue("appid", wx.APPID); data1.SetValue("noncestr", noncestr); data1.SetValue("package", "Sign=WXPay"); data1.SetValue("partnerid", wx.MCHID); data1.SetValue("prepayid", result.GetValue("prepay_id")); data1.SetValue("timestamp", timestamp); string sign = data1.MakeSign(SeIn.PayId); string wxstr = "{\"appid\":\"" + result.GetValue("appid") + "\",\"partnerid\":\"" + result.GetValue("mch_id") + "\",\"prepayid\":\"" + result.GetValue("prepay_id") + "\",\"pkg\":\"Sign=WXPay\",\"noncestr\":\"" + noncestr + "\",\"timestamp\":\"" + timestamp + "\",\"sign\":\"" + sign + "\",\"PaymentType\":\"5\",\"SubType\":\"1\",\"IsH5\":\"0\"}"; // str = "{\"message\":\"成功\",\"result\":100,\"data\":" + wxstr + "}"; inn = inn.ToResponse(ErrorCode.Code100); inn.ExtraData = JMP.TOOL.AesHelper.AesEncrypt(wxstr, ConfigurationManager.AppSettings["encryption"].ToString()); } else { PayApiDetailErrorLogger.UpstreamPaymentErrorLog("报错信息:支付通道异常", summary: "微信appid支付接口错误信息", channelId: SeIn.PayId); inn = inn.ToResponse(ErrorCode.Code104); } } catch (Exception E) { PayApiDetailErrorLogger.UpstreamPaymentErrorLog("报错信息:" + E.ToString(), summary: "微信appid支付接口错误信息", channelId: SeIn.PayId); inn = inn.ToResponse(ErrorCode.Code104); } return(inn); }
private void GetPaySign(HttpContext context) { //定义统一消息体 Core.Data.Entity.SystemEntity.MessageModel message = new Core.Data.Entity.SystemEntity.MessageModel(); //定义请求工具 HttpGetOrPost httpHelper = new HttpGetOrPost(); //定义重定向URL string redirect_url1 = HttpUtility.UrlEncode("https://www.yuming.com.cn/auth.aspx"); string redirect_url2 = HttpUtility.UrlEncode("https://www.yuming.com.cn/success.html"); var jsCode = Q("code", context); if (string.IsNullOrEmpty(jsCode)) { message.msg = "0"; message.data = ""; context.Response.Write(JsonConvert.SerializeObject(message)); return; } #region 第二步,获取openid string url2 = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={WechatJSAPIConfig.appid}&secret={WechatJSAPIConfig.appSecret}&code={jsCode}&grant_type=authorization_code"; /* 正确的json * { * "access_token":"ACCESS_TOKEN", * "expires_in":7200, * "refresh_token":"REFRESH_TOKEN", * "openid":"OPENID", * "scope":"SCOPE" * } */ string response2 = httpHelper.HttpGet(url2); WechatOAuthResponse oauth = JsonConvert.DeserializeObject <WechatOAuthResponse>(response2); if (oauth == null || !string.IsNullOrEmpty(oauth.errcode)) { message.msg = "0"; message.data = ""; context.Response.Write(JsonConvert.SerializeObject(message)); } //拿到OPENID var openid = oauth.openid; context.Session["openid"] = oauth.openid; #endregion #region 第三步获取access_token //注意该access_token与授权access_token不一样 string url3 = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={WechatJSAPIConfig.appid}&secret={WechatJSAPIConfig.appSecret}"; string response3 = httpHelper.HttpGet(url3); WechatAccessResponse access = JsonConvert.DeserializeObject <WechatAccessResponse>(response3); if (access == null || access.errcode != 0) { message.msg = "0"; message.data = ""; context.Response.Write(JsonConvert.SerializeObject(message)); } //拿到OPENID string access_token = access.access_token; #endregion #region 第四步,获取jsapi_ticket string url4 = $"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={access_token}&type=jsapi"; /* 正确的json * { * "errcode":0, * "errmsg":"ok", * "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA", * "expires_in":7200 * }*/ string response4 = httpHelper.HttpGet(url4); WechatTicketResponse ticket = JsonConvert.DeserializeObject <WechatTicketResponse>(response4); if (ticket == null || ticket.errcode != 0) { message.msg = "0"; message.data = ""; context.Response.Write(JsonConvert.SerializeObject(message)); } //记录ticket string jsapi_ticket = ticket.ticket; #endregion string timestamp = WxPayApi.GenerateTimeStamp(); string nonceStr = WxPayApi.GenerateNonceStr(); context.Session["timestamp"] = timestamp; context.Session["nonceStr"] = nonceStr; WxPayData configData = new WxPayData(); configData.SetValue("jsapi_ticket", jsapi_ticket); configData.SetValue("noncestr", nonceStr); configData.SetValue("timestamp", timestamp); configData.SetValue("url", $"https://www.yuming.com.cn/auth.aspx?code={jsCode}&state=STATE"); string sha1sign = configData.SHA1Sign(); var jsBridge = new { msg = "200", appId = WechatJSAPIConfig.appid, timeStamp = timestamp, nonceStr = nonceStr, sha1sign = sha1sign }; string jsApiData = JsonConvert.SerializeObject(jsBridge); context.Response.Write(jsApiData); }