protected void Page_Load(object sender, EventArgs e) { wid = MyCommFun.RequestInt("wid"); //授权 BLL.wx_userweixin bll = new BLL.wx_userweixin(); Model.wx_userweixin wxModel = bll.GetModel(wid); string code = MyCommFun.QueryString("code"); if (code == null || code.Trim() == "") { string thisUrl = MyCommFun.getTotalUrl(); string newUrl = OAuthApi.GetAuthorizeUrl(wxModel.AppId, thisUrl, "fukuan", OAuthScope.snsapi_base); Response.Redirect(newUrl); } else { var result = OAuthApi.GetAccessToken(wxModel.AppId, wxModel.AppSecret, code); openid = result.openid; } //授权结束 // logBll.AddLog("【微支付】微信预定", "paypage.aspx Page_Load", " 授权结束openid= " + openid, 1); try { int otid = MyCommFun.RequestInt("orderid"); otid_str = otid.ToString(); rpage = "/api/payment/paypage.aspx?showwxpaytitle=1&paytype=shop&wid=" + wid + "&openid=" + openid + "&orderid=" + otid_str; if (code == null || code.Trim() == "" || openid == "" || otid == 0 || wid == 0) { return; } //expireMinute = MyCommFun.RequestInt("expireminute"); //if (expireMinute == 0) //{ // expireMinute = 30; //} //else if (expireMinute == -1) //{ //如果为-1,则有限期间为1年 // expireMinute = 60 * 12 * 365; //} BLL.orders otBll = new BLL.orders(); Model.orders orderEntity = otBll.GetModel(otid, wid); WXLogs.AddLog("【微支付】微信预定", "paypage.aspx Page_Load", "orderEntity.order_no: " + orderEntity.order_no + "|orderEntity.order_amount:" + orderEntity.order_amount, 1); litout_trade_no.Text = orderEntity.order_no; litMoney.Text = orderEntity.order_amount.ToString(); litDate.Text = orderEntity.add_time.ToString(); //WxPayData(orderEntity.order_amount, orderEntity.id.ToString(), orderEntity.order_no, code);//老的接口 WxPayDataV3(orderEntity.order_amount, orderEntity.id.ToString(), orderEntity.order_no, code); } catch (Exception ex) { WXLogs.AddLog("【微支付】微信预定", "paypage.aspx Page_Load", "ex: " + ex.Message, 1); //MessageBox.ShowAndRedirect(this, "支付有问题:" + ex.Message, "/shop/index.aspx?wid=" + wid); } }
/// <summary> /// 关注时候处理 /// </summary> public string weipaiSubscribe(string openid, int wid) { BLL.wx_userweixin uwbll = new BLL.wx_userweixin(); string wxId = uwbll.GetwxId(wid);//原始Id if (wxId == null || wxId.Trim() == "") { return("wid参数错误"); } try { WeiXinPF.BLL.wx_paizhao_setting setBll = new WeiXinPF.BLL.wx_paizhao_setting(); WeiXinPF.Model.wx_paizhao_setting model = setBll.GetModelByWid(wid); if (model == null || model.isOpen == false) { return("未开启"); } Dictionary <string, string> parameters = new Dictionary <string, string>(); string url = model.initApiUrl;// "http://wphoto.betterwood.com:8080/Server/wechat/userinit.action"; string userid = openid; string sourceid = wxId;// "gh_e2d7eb82cb50"; 该用户的来源,即关注的哪一个微信公众账号)、(微信号)原始ID string timestamp = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString(); string v = "2000"; string signature = ""; parameters.Add("userid", openid); parameters.Add("sourceid", sourceid); parameters.Add("v", "2000"); parameters.Add("timestamp", timestamp); signature = GetBizSign(parameters); string postParam = "userid=" + userid + "&sourceid=" + sourceid + "×tamp=" + timestamp + "&v=" + v + "&signature=" + signature; string ret = Utils.HttpPost(url, postParam); Dictionary <string, object> dict = MyCommFun.JsonToDictionary(ret); string returnCode = dict["returncode"].ToString(); if (returnCode == "200") { //成功 WXLogs.AddLog(wid, "微拍用户关注时候的接口", "weipaiSubscribe", "奥尔图微拍接口调用成功了", 1); } else { WXLogs.AddLog(wid, "微拍用户关注时候的接口", "weipaiSubscribe", "奥尔图微拍接口调用失败:" + dict["returnmessage"].ToString(), 0); } return(returnCode); } catch (Exception ex) { WXLogs.AddLog(wid, "微拍用户关注时候的接口", "weipaiSubscribe", "报错:" + ex.Message, 0); return(ex.Message); } }
/* * req:<xml> * <appid><![CDATA[wxd745017dc584cdc9]]></appid> * <attach><![CDATA[5|160]]></attach> * <bank_type><![CDATA[CCB_DEBIT]]></bank_type> * <fee_type><![CDATA[CNY]]></fee_type> * <is_subscribe><![CDATA[Y]]></is_subscribe> * <mch_id><![CDATA[10011937]]></mch_id> * <nonce_str><![CDATA[9C82C7143C102B71C593D98D96093FDE]]></nonce_str> * <openid><![CDATA[o305WuBqoBjW2VYcF9KJjyxoTRXQ]]></openid> * <out_trade_no><![CDATA[b14112403325816]]></out_trade_no> * <result_code><![CDATA[SUCCESS]]></result_code> * <return_code><![CDATA[SUCCESS]]></return_code> * <sign><![CDATA[3C546ED181C1F56900C1112C871A399B]]></sign> * <sub_mch_id><![CDATA[10011937]]></sub_mch_id> * <time_end><![CDATA[20141124033307]]></time_end> * <total_fee>10</total_fee> * <trade_type><![CDATA[JSAPI]]></trade_type> * <transaction_id><![CDATA[1003530289201411240006160848]]></transaction_id> * </xml> */ protected void Page_Load(object sender, EventArgs e) { try { ProcessNotify(); } catch (Exception ex) { WriteContent("fail", "订单处理报异常catch_1"); WXLogs.AddLog("【微支付】微信预定", "notify_url Page_Load", "业务结果处理错误:" + ex.Message, 0); } }
/// <summary> ///【强制刷新】access_token值 /// access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。正常情况下access_token有效期为7200秒, /// 重复获取将导致上次获取的access_token失效。 /// 每日限额获取access_token.我们将access_token保存到数据库里,间隔时间为20分钟,从微信公众平台获得一次。 /// </summary> /// <returns></returns> public static string FlushAccessToken(int wid, out string error) { string token = ""; error = ""; try { wx_property_info pBll = new wx_property_info(); BLL.wx_userweixin wBll = new wx_userweixin(); Model.wx_userweixin weixininfo = wBll.GetModel(wid); if (weixininfo.AppId == null || weixininfo.AppSecret == null || weixininfo.AppId.Trim().Length <= 0 || weixininfo.AppSecret.Trim().Length <= 0) { error = "appId或者AppSecret未填写完全,请在[我的公众帐号]里补全信息!"; return(""); } var result = CommonApi.GetToken(weixininfo.AppId, weixininfo.AppSecret); token = result.access_token; //第一次插入微信属性表 if (!pBll.ExistsWid(wid, "access_token")) { //插入 pBll.AddAccess_Token(wid, token, result.expires_in); } else { WeiXinPF.Model.wx_property_info wxProperty = new WeiXinPF.Model.wx_property_info(); wxProperty = pBll.GetModelList("iName='access_token' and wid=" + wid)[0]; //更新到数据库里 wxProperty.iContent = token; wxProperty.createDate = DateTime.Now; wxProperty.expires_in = result.expires_in; pBll.Update(wxProperty); } } catch (Exception ex) { error = "获得access_token出错:" + ex.Message; WXLogs.AddLog(wid, "access_token", "获得access_token(FlushAccessToken)", error); } return(token); }
/// <summary> /// 处理关键词红包 /// </summary> /// <param name="keywords"></param> /// <param name="openid"></param> /// <param name="wid"></param> public string KeyWordsHongBao(string keywords, string openid, int wid) { BLL.wx_xjhongbao_action actBll = new BLL.wx_xjhongbao_action(); bool has = actBll.ExistsKeyWordsAction(wid, keywords);//这个时间段有红包 if (has) { //如果有关注时红包,则给人家发红包 Model.wx_xjhongbao_action actModel = actBll.GetKeyWordsModelByWid(wid, keywords); try { proecssSendHB(openid, wid, actModel); } catch (Exception ex) { WXLogs.AddLog(wid, "微信红包", actModel.act_name, "KeyWordsHongBao() 现金红包领取失败:" + ex.Message); } } return(""); }
/// <summary> /// 及时获得access_token值 /// access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。正常情况下access_token有效期为7200秒, /// 重复获取将导致上次获取的access_token失效。 /// 每日限额获取access_token.我们将access_token保存到数据库里,间隔时间为20分钟,从微信公众平台获得一次。 /// </summary> /// <returns></returns> public static string getAccessToken(int wid, out string error) { string token = ""; error = ""; try { wx_property_info pBll = new wx_property_info(); BLL.wx_userweixin wBll = new wx_userweixin(); Model.wx_userweixin weixininfo = wBll.GetModel(wid); if (weixininfo.AppId == null || weixininfo.AppSecret == null || weixininfo.AppId.Trim().Length <= 0 || weixininfo.AppSecret.Trim().Length <= 0) { error = "appId或者AppSecret未填写完全,请在[我的公众帐号]里补全信息!"; WXLogs.AddLog(wid, "access_token", "获得access_token", error); return(""); } WeiXinPF.Model.wx_property_info wxProperty = new WeiXinPF.Model.wx_property_info(); //第一次插入微信属性表 if (!pBll.ExistsWid(wid, "access_token")) { AccessTokenResult result = CommonApi.GetToken(weixininfo.AppId, weixininfo.AppSecret); token = result.access_token; pBll.AddAccess_Token(wid, token, result.expires_in); return(token); //WeChatAccountManager manager = WeChatAccountManager.CreateInstance(weixininfo.AppId, weixininfo.AppSecret); //Credential credential = new Credential(manager); //token = credential.AccessToken; //pBll.AddAccess_Token(wid, token, 7000); //return token; } wxProperty = pBll.GetModelList("iName='access_token' and wid=" + wid)[0]; double chajunSecond = (DateTime.Now - wxProperty.createDate.Value).TotalSeconds; if (chajunSecond >= wxProperty.expires_in) { //从微信平台重新获得access_token AccessTokenResult result = CommonApi.GetToken(weixininfo.AppId, weixininfo.AppSecret); token = result.access_token; //更新到数据库里 wxProperty.iContent = token; wxProperty.createDate = DateTime.Now; wxProperty.expires_in = result.expires_in; //WeChatAccountManager manager = WeChatAccountManager.CreateInstance(weixininfo.AppId, weixininfo.AppSecret); //Credential credential = new Credential(manager); //token = credential.AccessToken; ////更新到数据库里 //wxProperty.iContent = token; //wxProperty.createDate = DateTime.Now; //wxProperty.expires_in = 7000; //pBll.Update(wxProperty); } else { token = wxProperty.iContent; } } catch (Exception ex) { error = "获得access_token出错:" + ex.Message; WXLogs.AddLog(wid, "access_token", "获得access_token", error); } return(token); }
/// <summary> /// 获取jssdk 里的临时票据 /// </summary> /// <param name="wid"></param> /// <param name="error"></param> /// <returns></returns> public static string getJsApiTicket(int wid, out string error) { string atErr = ""; string accessToken = getAccessToken(wid, out atErr); if (atErr != "") { accessToken = FlushAccessToken(wid, out atErr); } if (accessToken == "") { error = "取accessToken值出现异常"; WXLogs.AddLog(wid, "getJsApiTicket", "获得getJsApiTicket", "WeiXinPF.WeiXinComm.getJsApiTicket" + error); return(""); } string token = ""; error = ""; try { wx_property_info pBll = new wx_property_info(); BLL.wx_userweixin wBll = new wx_userweixin(); Model.wx_userweixin weixininfo = wBll.GetModel(wid); if (weixininfo.AppId == null || weixininfo.AppSecret == null || weixininfo.AppId.Trim().Length <= 0 || weixininfo.AppSecret.Trim().Length <= 0) { error = "appId或者AppSecret未填写完全,请在[我的公众帐号]里补全信息!"; return(""); } WeiXinPF.Model.wx_property_info wxProperty = new WeiXinPF.Model.wx_property_info(); //第一次插入微信属性表 if (!pBll.ExistsWid(wid, "JsApiTicket")) { string type = "jsapi"; var url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type={1}", accessToken, type); JsApiTicketResult result = OneGulp.WeChat.HttpUtility.Get.GetJson <JsApiTicketResult>(url); token = result.ticket; //存入属性表 wxProperty.wid = wid; wxProperty.iName = "JsApiTicket"; wxProperty.iContent = token; wxProperty.createDate = DateTime.Now; wxProperty.expires_in = result.expires_in; wxProperty.count = 1; pBll.Add(wxProperty); return(token); } wxProperty = pBll.GetModelList("iName='JsApiTicket' and wid=" + wid)[0]; double chajunSecond = (DateTime.Now - wxProperty.createDate.Value).TotalSeconds; if (chajunSecond >= wxProperty.expires_in) { //从微信平台重新获得access_token string type = "jsapi"; var url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type={1}", accessToken, type); JsApiTicketResult result = OneGulp.WeChat.HttpUtility.Get.GetJson <JsApiTicketResult>(url); token = result.ticket; //更新到数据库里 wxProperty.iContent = token; wxProperty.createDate = DateTime.Now; wxProperty.expires_in = result.expires_in; pBll.Update(wxProperty); } else { token = wxProperty.iContent; } } catch (Exception ex) { error = "获得getJsApiTicket出错:" + ex.Message; WXLogs.AddLog(wid, "getJsApiTicket", "获得getJsApiTicket", "WeiXinPF.WeiXinComm.getJsApiTicket" + error); } return(token); }
/// <summary> /// 【微支付】 订单付款成功,处理订单:1将订单的状态改成付款完成; /// 李朴 add /// </summary> /// <param name="beforeFunName"></param> /// <param name="out_trade_no">商户订单号</param> /// <param name="transaction_id">订单交易号</param> /// <param name="result_code">支付结果</param> /// <param name="total_fee">付款金额(单位为分)</param> /// <param name="otid">订单临时表id</param> /// <returns>有错误则返回错误信息,正确,则返回空字符串</returns> public string ProcessPaySuccess_wx(string beforeFunName, string out_trade_no, string transaction_id, string result_code, int total_fee, int otid, int wid) { string payTmpType = "【微支付】"; decimal total_fee_d = (decimal)total_fee / 100; BLL.orders orderBll = new BLL.orders(); string funName = payTmpType + beforeFunName + " ProcessPaySuccess_wx "; WXLogs.AddLog(wid, "微支付", funName, "开始执行ProcessPaySuccess_wx方法[otid:" + otid + "]"); try { #region 数据同步前 IList <Model.orders> orderlist = orderBll.GetModelList("id=" + otid + " and order_no='" + out_trade_no + "'"); if (orderlist == null || orderlist.Count <= 0) { WXLogs.AddLog(wid, payTmpType, funName, "订单号【" + out_trade_no + "】订单号不存在", 0); return("订单号不存在"); } //这个暂时不处理 if (WXLogs.ExistsFlg((out_trade_no + otid))) { //如果已经处理过,则不再处理 return(""); } WXLogs.AddFlg(wid, payTmpType, funName, (out_trade_no + otid));//加标志,防止重复提交 Model.orders orderEntity = orderlist[0]; if (orderEntity.order_amount > total_fee_d) { return("付款的金额(" + total_fee_d + ")小于订单的预付款金额(" + orderEntity.order_amount + ")信息,直接退款"); } orderEntity.notify_id = ""; orderEntity.trade_no = transaction_id; orderEntity.pay_info = result_code; orderEntity.order_amount = total_fee_d; orderEntity.payment_time = DateTime.Now; orderEntity.status = 2; orderEntity.payment_status = 2; //判断是否需要立即发货 if (orderEntity.express_status == 0) { //立即发货 orderEntity.express_status = 2; orderEntity.express_time = DateTime.Now; //FaHuoProc fahuo = new FaHuoProc(); //BLL.wx_payment_wxpay payBll = new BLL.wx_payment_wxpay(); //Model.wx_payment_wxpay paymentInfo = payBll.GetModelByWid(wid); //Dictionary<string, object> fahuoDict = fahuo.fahuomgr(paymentInfo, orderEntity); //string errcode = fahuoDict["errcode"].ToString(); //string errmsg = fahuoDict["errmsg"].ToString(); //orderEntity.fahuoCode = errcode; //orderEntity.fahuoMsg = errmsg; //if (errcode == "0") //{ // orderEntity.express_status = 2; // orderEntity.express_time = DateTime.Now; //} //else //{ // orderEntity.express_status =1; //} } bool ret = orderBll.Update(orderEntity); //把订单里的商品库存减少 #region 减少库存 BLL.wx_shop_product spBll = new BLL.wx_shop_product(); BLL.orders oBll = new BLL.orders(); //根据订单号得到订单 Model.orders oModel = oBll.GetModelByNo(orderEntity.order_no); //得到所有订购商品 List <Model.order_goods> ogList = oModel.order_goods; //根据订购商品的数量修改库存 foreach (Model.order_goods item in ogList) { Model.wx_shop_product spModel = spBll.GetModel(item.goods_id); spModel.stock = spModel.stock - item.quantity; spBll.Update(spModel); } #endregion if (!ret) { WXLogs.AddLog(wid, payTmpType, funName, "订单号【" + out_trade_no + "】支付成功后处理数据失败", 0); return("订单号【" + out_trade_no + "】支付成功后处理数据失败"); } WXLogs.AddLog(payTmpType, funName, "订单号【" + out_trade_no + "】支付成功后,处理数据成功", 1); return(""); #endregion } catch (Exception ex) { WXLogs.AddLog(wid, payTmpType, funName, "订单号【" + out_trade_no + "】支付成功后处理数据同步出现错误:" + ex.Message, 0); return(null); } }
/// <summary> /// 处理回调的页面 /// </summary> private void ProcessNotify() { int wid = 0; string payTmpType = "【微支付】"; string funName = payTmpType + " notify_url ProcessNotify "; WXLogs.AddLog(payTmpType, funName, "从微支付返回到notify_url.aspx页面", 1); byte[] byts = new byte[Request.InputStream.Length]; Request.InputStream.Read(byts, 0, byts.Length); string req = System.Text.Encoding.Default.GetString(byts); req = Server.UrlDecode(req); WXLogs.AddLog(payTmpType, funName, "req:" + req, 1); //返回的状态码 string return_code = ReadXmlValue(req, "xml/return_code"); WXLogs.AddLog(payTmpType, "notify_url ProcessNotify", "返回的状态码return_code:" + return_code, 1); if (return_code.Trim().ToLower() == "fail") { string return_msg = ReadXmlValue(req, "xml/return_msg"); WXLogs.AddLog(payTmpType, funName, "订单处理错误:" + return_msg, 0); WriteContent("fail", "订单处理错误:" + return_msg); return; } string attach = ReadXmlValue(req, "xml/attach"); string[] attachArr = attach.Split('|'); wid = MyCommFun.Str2Int(attachArr[0]); int otid = MyCommFun.Str2Int(attachArr[1]); BLL.wx_payment_wxpay payBll = new BLL.wx_payment_wxpay(); Model.wx_payment_wxpay paymentInfo = payBll.GetModelByWid(wid); WXLogs.AddLog(wid, payTmpType, funName, "取到wid=" + wid, 1); string appId = ReadXmlValue(req, "xml/appid"); //公众账号id string mchId = ReadXmlValue(req, "xml/mch_id"); //商户号 string result_code = ReadXmlValue(req, "xml/result_code"); //业务结果 if (result_code.Trim().ToLower() == "fail") { //支付失败 string err_code = ReadXmlValue(req, "xml/err_code"); string err_code_des = ReadXmlValue(req, "xml/err_code_des"); WXLogs.AddLog(wid, payTmpType, funName, "业务结果处理错误err_code:" + err_code + "[err_code_des]:" + err_code_des, 0); WriteContent("fail", "业务结果处理错误err_code:" + err_code + "[err_code_des]:" + err_code_des); return; } //支付成功 string openid = ReadXmlValue(req, "xml/openid"); //金额,以分为单位 string total_fee = ReadXmlValue(req, "xml/total_fee"); string out_trade_no = ReadXmlValue(req, "xml/out_trade_no"); string transaction_id = ReadXmlValue(req, "xml/transaction_id"); WXLogs.AddLog(wid, payTmpType, "notify_url ProcessNotify", "支付成功了:openid=" + openid + " out_trade_no=" + out_trade_no + " transaction_id=" + transaction_id + " total_fee(分)=" + total_fee + " result_code=" + result_code + " orderid=" + otid + " wid=" + wid, 1); //------------------------------ //处理业务开始 //处理数据库逻辑 //注意交易单不要重复处理 //注意判断返回金额 //------------------------------ wxOrderTmpMgr Totbll = wxOrderTmpMgr.instance(); string ret = Totbll.ProcessPaySuccess_wx("notify_url", out_trade_no, transaction_id, result_code, MyCommFun.Str2Int(total_fee), otid, wid); ret = ret == "" ? "处理数据同步发送成功" : ret; WXLogs.AddLog(wid, payTmpType, funName, ret, 1); //------------------------------ //处理业务完毕 //------------------------------ //回复服务器处理成功 WriteContent("success"); }
/// <summary> /// 传图片 /// </summary> /// <param name="openid"></param> /// <param name="PicUrl"></param> /// <returns></returns> public string weipaiChuanTuPian(string openid, string PicUrl, int wid) { BLL.wx_userweixin uwbll = new BLL.wx_userweixin(); string wxId = uwbll.GetwxId(wid);//原始Id string returnCode = ""; WeiXinPF.BLL.wx_logs logBll = new WeiXinPF.BLL.wx_logs(); try { WeiXinPF.BLL.wx_paizhao_setting setBll = new WeiXinPF.BLL.wx_paizhao_setting(); WeiXinPF.Model.wx_paizhao_setting model = setBll.GetModelByWid(wid); if (model == null || model.isOpen == false) { return(""); } Dictionary <string, string> parameters = new Dictionary <string, string>(); string url = model.picApiUrl; // string userid = openid; string sourceid = wxId; // "gh_e2d7eb82cb50"; //该用户的来源,即关注的哪一个微信公众账号)、(微信号)原始ID string timestamp = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString(); string v = "2000"; string downurl = PicUrl; string signature = ""; parameters.Add("userid", openid); parameters.Add("sourceid", sourceid); parameters.Add("downurl", downurl); parameters.Add("timestamp", timestamp); parameters.Add("v", "2000"); signature = GetBizSign(parameters); string postParam = "userid=" + userid + "&downurl=" + downurl + "&sourceid=" + sourceid + "×tamp=" + timestamp + "&v=" + v + "&signature=" + signature; string ret = Utils.HttpPost(url, postParam); Dictionary <string, object> dict = MyCommFun.JsonToDictionary(ret); returnCode = dict["returncode"].ToString(); if (returnCode == "200") { //成功 WXLogs.AddLog(wid, "微拍传图的接口", "weipaiChuanTuPian", "奥尔图微拍接口调用成功了", 1); WeiXinPF.BLL.wx_paizhao_picinfo pBll = new WeiXinPF.BLL.wx_paizhao_picinfo(); WeiXinPF.Model.wx_paizhao_picinfo pic = new WeiXinPF.Model.wx_paizhao_picinfo(); pic.openid = openid; pic.picUrl = PicUrl; pic.createDate = DateTime.Now; pBll.Add(pic); return(dict["mentioninfo"].ToString()); } else { WXLogs.AddLog(wid, "微拍传图的接口", "weipaiChuanTuPian", "奥尔图微拍接口调用失败:" + dict["returnmessage"].ToString(), 0); return(dict["returnmessage"].ToString()); } } catch (Exception ex) { WXLogs.AddLog(wid, "微拍传图的接口", "weipaiChuanTuPian", "报错:" + ex.Message, 0); return("打印接口报错:" + ex.Message); } }
/// <summary> /// 处理发关注红包的逻辑 /// </summary> /// <param name="openid"></param> /// <param name="wid"></param> /// <param name="actModel"></param> public int proecssSendHB(string openid, int wid, Model.wx_xjhongbao_action actModel) { BLL.wx_xjhongbao_action actBll = new BLL.wx_xjhongbao_action(); BLL.wx_xjhongbao_base baseBll = new BLL.wx_xjhongbao_base(); Model.wx_xjhongbao_base baseModel = baseBll.GetModelByWid(wid); BLL.wx_payment_wxpay weixinPayBLL = new BLL.wx_payment_wxpay(); Model.wx_payment_wxpay weixinPayModel = weixinPayBLL.GetModelByWid(wid); if (baseModel == null || weixinPayModel == null || actModel == null) { return(0); } #region 取用户昵称--注释掉了 //string error = ""; //string accessToken=WeiXinCRMComm.getAccessToken(wid, out error); //if (error.Trim().Length > 0) //{ // WXLogs.AddErrLog(wid, "微信红包", actModel.act_name, "accessToken取值有错误error:"+error); // return; //} //string nick = UserApi.Info(accessToken, openid).nickname; #endregion //用户此次获得的红包(单位分) int hongbaoFen = 0; if (actModel.totalLqMoney >= actModel.totalMoney) { //1 红包金额已经领取完了,记录到日志 InsertToLQinfo(wid, actModel.id, openid, 0, DateTime.Parse("1970-1-1"), "", "", "", "", "红包余额不足,需要调整活动的金额"); return(0); } //2 判断该用户是否已经领取了 bool hasLQ = lqBll.ExistsOpenid(actModel.id, openid, actModel.lqType == 0 ? true : false); if (hasLQ) { //已经领取了 return(0); } int leftMoney = actModel.totalMoney.Value - actModel.totalLqMoney.Value;//剩余金额 //3 计算本次的红包 if (actModel.moneyType == 0) { //定额 hongbaoFen = actModel.min_value.Value; } else { //随机 Random rd = new Random(); hongbaoFen = rd.Next(actModel.min_value.Value, actModel.max_value.Value); } if (hongbaoFen >= leftMoney) { hongbaoFen = leftMoney; } //4 给用户发红包 string mchbillno = weixinPayModel.mch_id + DateTime.Now.ToString("yyyymmddHHmmss") + TenPayV3Util.BuildRandomStr(4); Model.wx_xjhongbao_lqinfo lqinfoEntity = new Model.wx_xjhongbao_lqinfo(); lqinfoEntity.wid = wid; lqinfoEntity.actionId = actModel.id; lqinfoEntity.openid = openid; lqinfoEntity.total_amount = hongbaoFen; lqinfoEntity.createDate = DateTime.Now; XmlDocument doc = new XmlDocument(); if (!SendHBBase(weixinPayModel, actModel, wid, openid, hongbaoFen, mchbillno, doc)) { //发红包的方法出现问题 WXLogs.AddErrLog(wid, "微信红包", actModel.act_name, "发现金红包底层方法报错。"); lqinfoEntity.Send_time = DateTime.Now; lqinfoEntity.mch_billno = mchbillno; lqinfoEntity.mch_id = weixinPayModel.mch_id; lqinfoEntity.hbstatus = "FAILED"; lqinfoEntity.send_type = "API"; lqinfoEntity.hb_type = "NORMAL"; lqinfoEntity.reason = "result_code:" + doc.InnerXml.ToString(); lqBll.Add(lqinfoEntity); //记录领取日志 WXLogs.AddLog(wid, "微信红包", actModel.act_name, "现金红包领取失败:" + doc.InnerXml.ToString()); return(0); } //5修改现金:1活动的领取金额增加;2用户的中奖记录增加 actModel = actBll.GetModel(actModel.id); actModel.totalLqMoney += hongbaoFen; actBll.Update(actModel); //6修改配置文件的领取金额; baseModel.totalLQMoney += hongbaoFen; baseBll.Update(baseModel); WXLogs.AddLog(wid, "微信红包", actModel.act_name, "现金红包领取成功2:" + doc.InnerXml.ToString()); lqinfoEntity.Send_time = MyCommFun.Obj2DateTime(MyCommFun.GetXmlNode("send_time", doc), DateTime.Now); lqinfoEntity.mch_billno = mchbillno; lqinfoEntity.mch_id = weixinPayModel.mch_id; lqinfoEntity.detail_id = MyCommFun.GetXmlNode("send_listid", doc); lqinfoEntity.hbstatus = "SUCCESS"; lqinfoEntity.send_type = "API"; lqinfoEntity.hb_type = "NORMAL"; lqinfoEntity.reason = ""; lqinfoEntity.remark = doc.InnerXml.ToString(); lqBll.Add(lqinfoEntity); WXLogs.AddLog(wid, "微信红包", actModel.act_name, "现金红包成功领取3:" + doc.InnerXml.ToString()); return(hongbaoFen); }
/// <summary> /// 最新接口调用 /// 2014-11-24 /// </summary> /// <param name="ttFee">支付金额(单位元)</param> /// <param name="busiBody">订单内容</param> /// <param name="out_trade_no">订单号</param> /// <param name="code"></param> protected void WxPayDataV3(decimal ttFee, string busiBody, string out_trade_no, string code) { BLL.wx_payment_wxpay wxPayBll = new BLL.wx_payment_wxpay(); Model.wx_payment_wxpay paymentInfo = wxPayBll.GetModelByWid(wid); BLL.wx_userweixin uwBll = new BLL.wx_userweixin(); Model.wx_userweixin uwEntity = uwBll.GetModel(wid); // logBll.AddLog(wid,"【微支付】微信预定", "paypage.aspx WxPayDataV3", "211 wid:" + wid, 1); //先设置基本信息 string MchId = paymentInfo.mch_id; // "1218574001";// string partnerKey = paymentInfo.paykey; // 商户支付密钥Key。登录微信商户后台,进入栏目【账户设置】【密码安全】【API 安全】【API 密钥】 string notify_url = "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx"; WXLogs.AddLog(wid, "【微支付】微信预定", "paypage.aspx WxPayDataV3", "uwEntity.AppId: " + uwEntity.AppId + "| uwEntity.AppSecret;" + uwEntity.AppSecret + "|code:" + code, 1); string timeStamp = ""; string nonceStr = ""; string paySign = ""; string sp_billno = out_trade_no; //当前时间 yyyyMMdd string date = DateTime.Now.ToString("yyyyMMdd"); if (null == sp_billno) { //生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一 sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28); } //创建支付应答对象 OneGulp.WeChat.MP.TenPayLibV3.RequestHandler packageReqHandler = new OneGulp.WeChat.MP.TenPayLibV3.RequestHandler(null); //初始化 packageReqHandler.Init(); //packageReqHandler.SetKey(""/*TenPayV3Info.Key*/); timeStamp = TenPayV3Util.GetTimestamp(); nonceStr = TenPayV3Util.GetNoncestr(); //设置package订单参数 packageReqHandler.SetParameter("appid", uwEntity.AppId); //公众账号ID packageReqHandler.SetParameter("mch_id", MchId); //商户号 packageReqHandler.SetParameter("nonce_str", nonceStr); //随机字符串 packageReqHandler.SetParameter("body", busiBody); //商品描述 packageReqHandler.SetParameter("attach", wid + "|" + busiBody); packageReqHandler.SetParameter("out_trade_no", sp_billno); //商家订单号 packageReqHandler.SetParameter("total_fee", ((int)(ttFee * 100)).ToString()); //商品金额,以分为单位(money * 100).ToString() packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress); //用户的公网ip,不是商户服务器IP packageReqHandler.SetParameter("notify_url", notify_url); //接收财付通通知的URL packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString()); //交易类型 packageReqHandler.SetParameter("openid", openid); //用户的openId string sign = packageReqHandler.CreateMd5Sign("key", partnerKey); packageReqHandler.SetParameter("sign", sign); //签名 string data = packageReqHandler.ParseXML(); var result = TenPayV3Helper.Unifiedorder(data); var res = XDocument.Parse(result); prepayId = res.Element("xml").Element("prepay_id").Value; //设置支付参数 OneGulp.WeChat.MP.TenPayLibV3.RequestHandler paySignReqHandler = new OneGulp.WeChat.MP.TenPayLibV3.RequestHandler(null); paySignReqHandler.SetParameter("appId", uwEntity.AppId); paySignReqHandler.SetParameter("timeStamp", timeStamp); paySignReqHandler.SetParameter("nonceStr", nonceStr); paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId)); paySignReqHandler.SetParameter("signType", "MD5"); paySign = paySignReqHandler.CreateMd5Sign("key", partnerKey); packageValue = ""; packageValue += " \"appId\": \"" + uwEntity.AppId + "\", "; packageValue += " \"timeStamp\": \"" + timeStamp + "\", "; packageValue += " \"nonceStr\": \"" + nonceStr + "\", "; packageValue += " \"package\": \"" + string.Format("prepay_id={0}", prepayId) + "\", "; packageValue += " \"signType\": \"MD5\", "; packageValue += " \"paySign\": \"" + paySign + "\""; }