扫二维码关注服务号同时发现金红包
2018-06-22 07:32:10来源:未知 阅读 ()
本文只是记录一下自己最近开发的一个小功能,方便以后查看。
一、需求原文如下:
1.vip微信参数配置
1)是否启用
2)设置每单最大红包金额 (例如5 )
3)设置各类别 红包金额范围
钻石 3-5
黄金 2-3 等等
2.质量保证单
打印二维码 参数传销售门店 以及销售单号
客户扫码
1)自动关注服务号
2)自动匹配客户档案
openid 匹配到档案的增加积分以及总积分 ,
未匹配到档案的 客户填写 姓名,手机号 如果手机号匹配到记录 自动将客户档案关联上
手机号也未匹配到记录 自动建立档案(自动插入所属分销商id,微信openid,姓名,手机号,总积分,剩余积分 必填项添默认值)
3)根据用户结果 自动关联客户消费记录
4)根据积分规则判断消费完客户是否达成升级标准(客户等级只升不降)
5)根据参数配置 自动发送一个红包给客户 同单多次扫描只发送一次红包.
红包规则 1.判断是否启用 没有启用不发送
2.发送红包时 取明细条码里面 红包金额上限最大的 记录 随机生成一个金额的红包发送
例如 客户购买2件货品 钻石 3-5 黄金2-3
那么随机发送一个 3-5元的红包给客户
(暂不考虑销退的情况)
二、需求理解:简单来说就是门店下单时需要在质保单上面打印上我们的服务号二维码(二维码参数带上订单号),扫码时根据openid(客户微信号在我们的服务号唯一的标示)匹配客户表,如果之前已经存在,就根据单号和积分规则计算客户的积分,没发过红包的单就发送一个根据类别配置金额的红包给客户。如果openid没有匹配到就给个链接填写vip信息,之后发送红包和消费记录,同时计算积分。
三、实操
1.服务号申请 2.开通支付功能,下载证书。 3.调用带参数的二维码接口生成二维码。4.响应关注事件(判断用户身份,计算积分,发送红包等)
using Common; using CommonHelp; using JDF.ERP.Common.Model; using JDF.ERP.Common.WeiXin; using JDF.ERP.CRM.BLL; using JDF.ERP.Invoicing.BLL; using JDF.ERP.PlatConfig.BLL; using JDF.ERP.Style.BLL; using LitJson; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Web; using System.Web.Http; using System.Xml; using JDF.ERP.Common.Tencent; using JDF.ERP.SystemManage.BLL; using System.IO; using System.Security.Cryptography; using Newtonsoft.Json; using JDF.ERP.Sale.BLL; namespace JDF.ERP.WebAPI.Control { /// <summary> /// 金大福微信服务号交互响应类 /// </summary> public class JDFWXServiceController : ApiController { WeiXinHelp objWeiXinHelp = new WeiXinHelp(); WeiXinQiYeHelp objWeiXinQiYeHelp = new WeiXinQiYeHelp(); Log objLog = new Log(); /// <summary> /// 用于处理金大福服务号的交互 /// </summary> /// <returns></returns> [HttpGet] [HttpPost] public HttpResponseMessage Service() { var response = Request.CreateResponse(HttpStatusCode.OK); var act = Misc.GetRequstValue("act"); var ordersNo = Misc.GetRequstValue("no"); //微信加密签名,signature结合了开发者填写的token参数和请求timestamp参数、nonce参数 var signature = Misc.GetRequstValue("signature"); var timestamp = Misc.GetRequstValue("timestamp");//时间戳 var nonce = Misc.GetRequstValue("nonce");//随机数 var echostr = Misc.GetRequstValue("echostr"); //随机字符串 objLog.Action("微信接入验证:" + signature + "|" + timestamp + "|" + echostr); #region 是否是验证操作(这个只会在申请成为开发者时验证一次) if (!string.IsNullOrWhiteSpace(echostr)) { response.Content = new StringContent(ValidateWX(signature, timestamp, nonce, echostr), Encoding.UTF8); return response; } #endregion #region 创建菜单 if (act != null) { if (act == "create") { //CreateMenu1("wx30c0a5c885bba30d", "dd3f65ae813d4b14c647859b91e0e776"); //生成带参数的二维码 string responseJson = objWeiXinHelp.GetQrcodeYJ("wx30c0a5c885bba30d", "dd3f65ae813d4b14c647859b91e0e776", ordersNo); //S0064216072100364 S0065916072100349 S0065516072200148 S0064216072100364 S0106216072200151 var DynamicObject = JsonConvert.DeserializeObject<dynamic>(responseJson); string ticket = DynamicObject.ticket; string path = Misc.GetPath("/images"); objWeiXinHelp.GetCodePic(ticket, path); //发送模板消息 //string url = ConfigHelper.GetConfigString("OutERPURL"); //objWeiXinHelp.SendUserInfoAdd("okehNt44afCOnburT5b7dXHivlSc", url + "WeiXinCoustomerAdd/Index?OrderNo=" + "S12022813235758" + "&OpenID=okehNt44afCOnburT5b7dXHivlSc", "请您完善您的金大福VIP信息", "完善资料有红包哟", DateTime.Now.ToShortDateString(), "感谢您对金大福的关注!"); //objWeiXinHelp.FocusLike(); } } #endregion string postData = objWeiXinHelp.getPostInput(); //微信传过来的数据 xml格式的 XmlDocument xmlDoc = new XmlDocument(); if (postData != "") { var bOrder_S = BOrder_S.GetInstance();//销售表 BCusAccount bCusAccount = BCusAccount.GetInstance();//账户表 xmlDoc.LoadXml(postData); XmlNode msgTypeNode = xmlDoc.ChildNodes[0].SelectSingleNode("MsgType"); string msgType = (msgTypeNode == null ? "" : msgTypeNode.InnerText); XmlNode eventKeyNode = xmlDoc.ChildNodes[0].SelectSingleNode("Event"); string eventKey = (eventKeyNode == null ? "" : eventKeyNode.InnerText); XmlNode orderNode = xmlDoc.ChildNodes[0].SelectSingleNode("EventKey"); string orderNO = (orderNode == null ? "" : orderNode.InnerText); if (msgType == "text") { //获取用户消息 objLog.Action("微信接受类型是文本:" + postData); //GetUserSendMsg(postData); } //客户扫码事件 else if (eventKey.ToLower() == "scan" || eventKey.ToLower() == "subscribe") { //发送方帐号的openid XmlNode fromUserName = xmlDoc.ChildNodes[0].SelectSingleNode("FromUserName"); string openId = (fromUserName == null ? "" : fromUserName.InnerText); if (String.IsNullOrEmpty(orderNO)) { return response; } //获取销售订单 var order_s = bOrder_S.GetAllByCondition(new SEOrder_S() { OrderNo = orderNO }).FirstOrDefault(); if (order_s == null) { return response; } #region 验证条码是否已经被其他人扫过 if (order_s != null && !string.IsNullOrEmpty(order_s.SVIPNo)) { var cust = BCustomer.GetInstance().GetAllByCondition(new SECustomer() { VIPNo = order_s.SVIPNo }).FirstOrDefault(); if (cust != null) { if (!string.IsNullOrEmpty(cust.Cus_OpenID) && cust.Cus_OpenID != openId) //证明这个二维码已经被扫描过了,不能再次扫描 { objWeiXinHelp.SendTextMess(openId, "本条码已扫描过了,感谢您的关注"); return response; } } } #endregion var coutoms = BCustomer.GetInstance().GetAllByCondition(new SECustomer() { Cus_OpenID = openId }).FirstOrDefault(); //本单还没有计算过积分 if (string.IsNullOrEmpty(order_s.SVIPNo)) { if (coutoms != null) //消费用户已经存在 { bOrder_S.ProcessVip(orderNO, coutoms, order_s); //发送消费记录 var agentName = BAgent.GetInstance().GetOneByKeyID(order_s.SAgentID.Value).AgentName; var levelName = BCusLevel.GetInstance().GetOneByKeyID(coutoms.CusALevel.Value).CusLevelName; objWeiXinHelp.SendShoppingList(openId, "", "尊敬的" + coutoms.CusName + ",您的消费信息如下:", coutoms.VIPNo, agentName, order_s.TotalRealSalePrice + "元", "总积" + coutoms.CusATotalPoint + "分,会员等级为" + levelName); // 发红包 bOrder_S.SendRedPack(orderNO, coutoms.CustomerID, openId); } else //根据openid不存在 { string url = ConfigHelper.GetConfigString("OutERPURL"); //发送一个注册身份的连接 objWeiXinHelp.SendUserInfoAdd(openId, url + "WeiXinCoustomerAdd/Index?OrderNo=" + orderNO + "&OpenID="+openId, "请您完善您的金大福VIP信息", "完善资料有红包哟", DateTime.Now.ToShortDateString(), "感谢您对金大福的关注!"); } } else { if (coutoms==null) { coutoms = BCustomer.GetInstance().GetAllByCondition(new SECustomer() { VIPNo = order_s.SVIPNo }).FirstOrDefault(); coutoms.Cus_OpenID = openId; BCustomer.GetInstance().UpdateOne(coutoms); //更新openid } //发送消费记录 var agentName = BAgent.GetInstance().GetOneByKeyID(order_s.SAgentID.Value).AgentName; var levelName = BCusLevel.GetInstance().GetOneByKeyID(coutoms.CusALevel.Value).CusLevelName; objWeiXinHelp.SendShoppingList(openId, "", "尊敬的" + coutoms.CusName + ",您的消费信息如下:", coutoms.VIPNo, agentName, order_s.TotalRealSalePrice + "元", "总积" + coutoms.CusATotalPoint + "分,会员等级为" + levelName); // 发红包 bOrder_S.SendRedPack(orderNO, coutoms.CustomerID, openId); } } else { objLog.Action("微信接受类型开始,指令:" + postData); //获取指令 GetMenuClickType(postData); } } return response; } /// <summary> /// 获取用户关注事件 /// </summary> public void GetSubscribe(string postData) { StringBuilder log = new StringBuilder(); StringBuilder str = new StringBuilder(); log.Append("====start====="); try { //string postData = getPostInput(); XmlDocument xmlDoc = new XmlDocument(); log.Append("postData:" + postData); //objWeiXinQiYeHelp.SendNewMess("4289", "", "错误日志3 有人关注了", postData.ToString()); if (postData != "") { log.Append(postData); xmlDoc.LoadXml(postData); XmlNode toUserNameNode = xmlDoc.ChildNodes[0].SelectSingleNode("ToUserName"); XmlNode fromUserNameNode = xmlDoc.ChildNodes[0].SelectSingleNode("FromUserName"); XmlNode eventKeyNode = xmlDoc.ChildNodes[0].SelectSingleNode("Event"); string toUserName = toUserNameNode.InnerText; string fromUserName = fromUserNameNode.InnerText; string eventKey = eventKeyNode.InnerText; string url = ""; string fromWxID = fromUserName; //objWeiXinQiYeHelp.SendNewMess("4289", "", "错误日志4", eventKey); if (eventKey == "subscribe") { string responseJson = objWeiXinHelp.GetQrcodeYJ("wx30c0a5c885bba30d", "dd3f65ae813d4b14c647859b91e0e776", "S12022813235758"); xmlDoc.LoadXml(postData); var DynamicObject = JsonConvert.DeserializeObject<dynamic>(responseJson); string ticket = DynamicObject.ticket; str.Append("<xml>"); str.Append("<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>"); str.Append("<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>"); str.Append("<CreateTime>" + CDtoInt(DateTime.Now) + "</CreateTime>"); str.Append("<MsgType><![CDATA[text]]></MsgType>"); str.Append("<Content><![CDATA[感谢关注金大福官方公众号。\r\n 1、点击屏幕右上角菜单→查看历史消息,查看金大福最近资讯 \r\n 2、屏幕下方菜单体验客户关怀 \r\n 更多金大福最新资讯,请随时订阅查看]]></Content>"); str.Append("</xml>"); } } } catch (Exception ex) { log.Append(ex.ToString()); } finally { //Common.PageValidate.WriteFile(log.ToString()); //response.Write(str.ToString()); } } /// <summary> /// 创建单个菜单 /// </summary> /// <param name="appId"></param> /// <param name="appSecret"></param> /// <returns></returns> public bool CreateMenu1(string appId, string appSecret) { var result = false; try { string access_token = objWeiXinHelp.GetAccess_token(appId, appSecret); string url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + access_token + ""; StringBuilder menuData = new StringBuilder(); menuData.Append("{"); menuData.Append(" \"button\":["); menuData.Append(" { "); menuData.Append(" \"type\":\"view\","); menuData.Append(" \"name\":\"珠宝商城\","); menuData.Append(" \"url\":\"http://m.weigouyi.com/160322095509642770.html?fxshopid=160419233546048481\""); menuData.Append(" },"); menuData.Append(" {"); menuData.Append(" \"name\":\"个人中心\","); menuData.Append(" \"sub_button\":["); menuData.Append(" {"); menuData.Append(" \"type\":\"view\","); menuData.Append(" \"name\":\"会员注册\","); menuData.Append(" \"url\":\"http://p.weigouyi.com/m/Login.shtml?comid=160322095509642770&lu=http%3a%2f%2fi.weigouyi.com%2fdefault.aspx%3fcomid%3d160322095509642770\""); menuData.Append(" },"); menuData.Append(" {"); menuData.Append(" \"type\":\"click\","); menuData.Append(" \"name\":\"店铺绑定\","); menuData.Append(" \"key\":\"dpbd\""); menuData.Append(" },"); menuData.Append(" {"); menuData.Append(" \"type\":\"click\","); menuData.Append(" \"name\":\"金大福18周年庆\","); menuData.Append(" \"key\":\"ktf\""); menuData.Append(" },"); menuData.Append(" {"); menuData.Append(" \"type\":\"click\","); menuData.Append(" \"name\":\"售后服务\","); menuData.Append(" \"key\":\"tswq\""); menuData.Append(" },"); menuData.Append(" {"); menuData.Append(" \"type\":\"click\","); menuData.Append(" \"name\":\"投诉维权\","); menuData.Append(" \"key\":\"tswq2\""); menuData.Append(" }]"); menuData.Append(" },"); menuData.Append(" {"); menuData.Append(" \"name\":\"品牌速递\","); menuData.Append(" \"sub_button\":["); menuData.Append(" { "); menuData.Append(" \"type\":\"click\","); menuData.Append(" \"name\":\"品牌介绍\","); menuData.Append(" \"key\":\"ppjs\""); menuData.Append(" },"); menuData.Append(" {"); menuData.Append(" \"type\":\"click\","); menuData.Append(" \"name\":\"联系我们\","); menuData.Append(" \"key\":\"lxwm\""); menuData.Append(" },"); menuData.Append(" {"); menuData.Append(" \"type\":\"click\","); menuData.Append(" \"name\":\"新品抢鲜\","); menuData.Append(" \"key\":\"xpqx\""); menuData.Append(" },"); menuData.Append(" {"); menuData.Append(" \"type\":\"click\","); menuData.Append(" \"name\":\"火热活动\","); menuData.Append(" \"key\":\"hrhd\""); menuData.Append(" },"); //menuData.Append(" {"); //menuData.Append(" \"type\":\"click\","); //menuData.Append(" \"name\":\"现场摇一摇\","); //menuData.Append(" \"key\":\"xcyj\""); //menuData.Append(" }]"); menuData.Append(" }]"); menuData.Append(" }"); string res = objWeiXinHelp.postResponse(url, menuData.ToString()); JsonData jd = JsonMapper.ToObject(res); if (jd["errcode"] != null) { if (jd["errcode"].ToString() == "0") { result = true; } else { objLog.Action(jd["errcode"].ToString()); } } } catch { } return result; //response.Write(access_token); } /// <summary> /// 获取菜单点击事件 /// </summary> /// <param name="appId"></param> /// <param name="appSecret"></param> /// <returns></returns> public void GetMenuClickType(string postData) { StringBuilder log = new StringBuilder(); StringBuilder str = new StringBuilder(); log.Append("====start====="); try { XmlDocument xmlDoc = new XmlDocument(); //objWeiXinQiYeHelp.SendNewMess("4289", "", "错误日志5", postData); if (postData != "") { log.Append(postData); xmlDoc.LoadXml(postData); XmlNode toUserNameNode = xmlDoc.ChildNodes[0].SelectSingleNode("ToUserName"); XmlNode fromUserNameNode = xmlDoc.ChildNodes[0].SelectSingleNode("FromUserName"); XmlNode eventKeyNode = xmlDoc.ChildNodes[0].SelectSingleNode("EventKey"); string toUserName = toUserNameNode.InnerText; string fromUserName = fromUserNameNode.InnerText; string eventKey = eventKeyNode.InnerText; log.Append(eventKey); string url = ""; string fromWxID = fromUserName; //objWeiXinQiYeHelp.SendNewMess("4289", "", "错误日志6", eventKey); switch (eventKey.Trim()) { case "zbsc"://珠宝商城 string indexUrl = url; str.Append("<xml>"); str.Append("<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>"); str.Append("<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>"); str.Append("<CreateTime>" + CDtoInt(DateTime.Now) + "</CreateTime>"); str.Append("<MsgType><![CDATA[news]]></MsgType>"); str.Append("<ArticleCount>1</ArticleCount>"); str.Append("<Articles>"); str.Append("<item>"); str.Append("<Title><![CDATA[【珠宝商城】珠宝雕刻时光 微店拉近你我]]></Title>"); str.Append("<Description><![CDATA[功能开发中,敬请期待...]]></Description>"); str.Append("<PicUrl><![CDATA[http://wxs.zhubaoq.com/jdf/zbsc.jpg]]></PicUrl>"); str.Append("<Url><![CDATA[]]></Url>"); str.Append("</item>"); str.Append("</Articles>"); str.Append("</xml>"); break; case "tswq"://售后服务 str.Append("<xml>"); str.Append("<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>"); str.Append("<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>"); str.Append("<CreateTime>" + CDtoInt(DateTime.Now) + "</CreateTime>"); str.Append("<MsgType><![CDATA[text]]></MsgType>"); str.Append("<Content><![CDATA[尊敬的用户:如果您对我们网站的商品及服务有任何的投诉与建议,请您联系我们的客服人员,我们将竭诚为您服务,为此给您带来的不便请您原谅。客服热线:4008-826-068 ;客服邮箱:planning@mailking.com.cn]]></Content>"); str.Append("</xml>"); break; case "wddd"://我的订单 str.Append("<xml>"); str.Append("<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>"); str.Append("<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>"); str.Append("<CreateTime>" + CDtoInt(DateTime.Now) + "</CreateTime>"); str.Append("<MsgType><![CDATA[news]]></MsgType>"); str.Append("<ArticleCount>1</ArticleCount>"); str.Append("<Articles>"); str.Append("<item>"); str.Append("<Title><![CDATA[【我的订单】敬备香茗 恭候亲临]]></Title>"); str.Append("<Description><![CDATA[功能开发中,敬请期待...]]></Description>"); str.Append("<PicUrl><![CDATA[http://wxs.zhubaoq.com/jdf/wddd.jpg]]></PicUrl>"); str.Append("<Url><![CDATA[]]></Url>"); str.Append("</item>"); str.Append("</Articles>"); str.Append("</xml>"); break; case "fjmd"://附近门店 str.Append("<xml>"); str.Append("<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>"); str.Append("<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>"); str.Append("<CreateTime>" + CDtoInt(DateTime.Now) + "</CreateTime>"); str.Append("<MsgType><![CDATA[news]]></MsgType>"); str.Append("<ArticleCount>1</ArticleCount>"); str.Append("<Articles>"); str.Append("<item>"); str.Append("<Title><![CDATA[【附近门店】传承发展 人文为本]]></Title>"); str.Append("<Description><![CDATA[功能开发中,敬请期待...]]></Description>"); str.Append("<PicUrl><![CDATA[http://wxs.zhubaoq.com/jdf/fjmd.jpg]]></PicUrl>"); str.Append("<Url><![CDATA[]]></Url>"); str.Append("</item>"); str.Append("</Articles>"); str.Append("</xml>"); break; case "tswq2"://投诉维权 str.Append("<xml>"); str.Append("<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>"); str.Append("<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>"); str.Append("<CreateTime>" + CDtoInt(DateTime.Now) + "</CreateTime>"); str.Append("<MsgType><![CDATA[news]]></MsgType>"); str.Append("<ArticleCount>1</ArticleCount>"); str.Append("<Articles>"); str.Append("<item>"); str.Append("<Title><![CDATA[【投诉维权】传承发展 人文为本]]></Title>"); str.Append("<Description><![CDATA[功能开发中,敬请期待...]]></Description>"); str.Append("<PicUrl><![CDATA[http://wxs.zhubaoq.com/jdf/tswq.jpg]]></PicUrl>"); str.Append("<Url><![CDATA[]]></Url>"); str.Append("</item>"); str.Append("</Articles>"); str.Append("</xml>"); break; case "ppjs"://品牌介绍 str.Append("<xml>"); str.Append("<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>"); str.Append("<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>"); str.Append("<CreateTime>" + CDtoInt(DateTime.Now) + "</CreateTime>"); str.Append("<MsgType><![CDATA[news]]></MsgType>"); str.Append("<ArticleCount>1</ArticleCount>"); str.Append("<Articles>"); str.Append("<item>"); str.Append("<Title><![CDATA[【品牌介绍】卓金品质 福享天成]]></Title>"); str.Append("<Description><![CDATA[金大福珠宝有限公司成立于1997年6月10日,是专业从事黄金、K金、铂金、钻石、翡翠及其它珠宝饰品的生产、加工、批发、零售及进出口业务的大型珠宝专业公司。...]]></Description>"); str.Append("<PicUrl><![CDATA[http://120.24.182.226:81/images/ppjs.jpg]]></PicUrl>"); str.Append("<Url><![CDATA[http://120.24.182.226:81/brand_introduce.html]]></Url>"); str.Append("</item>"); str.Append("</Articles>"); str.Append("</xml>"); break; case "lxwm"://联系我们 str.Append("<xml>"); str.Append("<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>"); str.Append("<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>"); str.Append("<CreateTime>" + CDtoInt(DateTime.Now) + "</CreateTime>"); str.Append("<MsgType><![CDATA[text]]></MsgType>"); str.Append("<Content><![CDATA[电话/TEL:0755-25195222 传真/FAX:0755-25195386 电邮/E-MAIL:KingTaiFook@mailking.com.cn 邮编/P.C:518001 售后服务电话:400-882-6068 联系地址:深圳市罗湖区国贸商业大厦28-30楼]]></Content>"); str.Append("</xml>"); break; case "xpqx"://新品抢鲜 str.Append("<xml>"); str.Append("<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>"); str.Append("<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>"); str.Append("<CreateTime>" + CDtoInt(DateTime.Now) + "</CreateTime>"); str.Append("<MsgType><![CDATA[news]]></MsgType>"); str.Append("<ArticleCount>1</ArticleCount>"); str.Append("<Articles>"); str.Append("<item>"); str.Append("<Title><![CDATA[【新品抢鲜】璀璨星空 闪耀梦想]]></Title>"); str.Append("<Description><![CDATA[金大福珠宝有限公司成立于1997年6月10日,是专业从事黄金、K金、铂金、钻石、翡翠及其它珠宝饰品的生产、加工、批发、零售及进出口业务的大型珠宝专业公司。...]]></Description>"); str.Append("<PicUrl><![CDATA[http://120.24.182.226:81/images/xpqx.jpg]]></PicUrl>"); str.Append("<Url><![CDATA[http://120.24.182.226:81/brand_new.html]]></Url>"); str.Append("</item>"); str.Append("</Articles>"); str.Append("</xml>"); break; case "hrhd"://火热活动 str.Append("<xml>"); str.Append("<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>"); str.Append("<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>"); str.Append("<CreateTime>" + CDtoInt(DateTime.Now) + "</CreateTime>"); str.Append("<MsgType><![CDATA[news]]></MsgType>"); str.Append("<ArticleCount>1</ArticleCount>"); str.Append("<Articles>"); str.Append("<item>"); str.Append("<Title><![CDATA[【火热活动】寻找星空使者]]></Title>"); str.Append("<Description><![CDATA[一个来自“星空”的呼唤!圣诞夜,让我们相约金大福!]]></Description>"); str.Append("<PicUrl><![CDATA[http://120.24.182.226:81/images/hotActive1.jpg]]></PicUrl>"); str.Append("<Url><![CDATA[http://120.24.182.226:81/hotActicve.html]]></Url>"); str.Append("</item>"); str.Append("</Articles>"); str.Append("</xml>"); break; case "dpbd"://店铺绑定 str.Append("<xml>"); str.Append("<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>"); str.Append("<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>"); str.Append("<CreateTime>" + CDtoInt(DateTime.Now) + "</CreateTime>"); str.Append("<MsgType><![CDATA[text]]></MsgType>"); str.Append("<Content><![CDATA[请输入您要绑定的微信号:格式为:【dpbd微信号】;此功能目前提供给门店管理员使用!]]></Content>"); str.Append("</xml>"); break; case "ktf"://16周庆典 str.Append("<xml>"); str.Append("<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>"); str.Append("<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>"); str.Append("<CreateTime>" + CDtoInt(DateTime.Now) + "</CreateTime>"); str.Append("<MsgType><![CDATA[text]]></MsgType>"); str.Append("<Content><![CDATA[请输入您要绑定的微信号或者手机号:格式为:【ktf微信号或者ktf手机号】;此功能目前提供给特约嘉宾使用!]]></Content>"); str.Append("</xml>"); break; } log.Append(str); } } catch (Exception ex) { log.Append(ex.ToString()); objLog.Action(log.ToString()); } finally { //response.Write(str.ToString()); } } /// <summary> /// DateTime时间格式转换为Unix时间戳格式 /// </summary> /// <param name="time"></param> /// <returns></returns> public int CDtoInt(System.DateTime time) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); return (int)(time - startTime).TotalSeconds; } /// <summary> /// 微信接入验证 /// </summary> public string ValidateWX(string signature, string timestamp, string nonce, string echostr) { string token = "tokentest"; if (!String.IsNullOrWhiteSpace(signature) && !String.IsNullOrWhiteSpace(timestamp) && !String.IsNullOrWhiteSpace(nonce) && !String.IsNullOrWhiteSpace(echostr)) { objLog.Action(signature + "|" + timestamp + "|" + nonce + "|" + echostr); string[] ArrTmp = { token, timestamp, nonce }; Array.Sort(ArrTmp); //字典排序 string tmpStr = string.Join("", ArrTmp); tmpStr = SHA1_Encrypt(tmpStr); // tmpStr = tmpStr.ToLower(); objLog.Action(tmpStr + "|" + signature); if (tmpStr == signature) { return echostr; } else { return echostr; } } return echostr; } /// <summary> /// 对字符串进行SHA1加密 /// </summary> /// <param name="strIN">需要加密的字符串</param> /// <returns>密文</returns> public string SHA1_Encrypt(string Source_String) { byte[] StrRes = Encoding.Default.GetBytes(Source_String); HashAlgorithm iSHA = new SHA1CryptoServiceProvider(); StrRes = iSHA.ComputeHash(StrRes); StringBuilder EnText = new StringBuilder(); foreach (byte iByte in StrRes) { EnText.AppendFormat("{0:x2}", iByte); } return EnText.ToString(); } } }
1 using Common; 2 using LitJson; 3 using System; 4 using System.Collections.Generic; 5 using System.Configuration; 6 using System.IO; 7 using System.Linq; 8 using System.Net; 9 using System.Security.Cryptography; 10 using System.Security.Cryptography.X509Certificates; 11 using System.Text; 12 using System.Threading.Tasks; 13 using System.Web; 14 15 namespace JDF.ERP.Common.WeiXin 16 { 17 public class WeiXinHelp 18 { 19 20 21 /// <summary> 22 /// 获取Access_token 23 /// </summary> 24 /// <param name="appId"></param> 25 /// <param name="appSecret"></param> 26 /// <returns></returns> 27 public string GetAccess_token(string appId, string appSecret) 28 { 29 string str = ""; 30 string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", HttpContext.Current.Server.UrlPathEncode(appId.Trim()).Replace("%e2%80%8b", ""), HttpContext.Current.Server.UrlPathEncode(appSecret.Trim()).Replace("%e2%80%8b", "")); 31 string res = getResponse(url); 32 JsonData jd = JsonMapper.ToObject(res); 33 if (jd["access_token"] != null) 34 { 35 str = jd["access_token"].ToString(); 36 } 37 return str; 38 } 39 40 /// <summary> 41 /// 微信发送补全用户资料提醒 42 /// </summary> 43 /// <param name="ToOpenID">openid</param> 44 /// <param name="LinkURL">连接</param> 45 /// <param name="TopMess">标题</param> 46 /// <param name="Code">补充内容</param> 47 /// <param name="SendTime">时间</param> 48 /// <param name="Memark">备注</param> 49 /// <returns></returns> 50 public string SendUserInfoAdd(string ToOpenID, string LinkURL, string TopMess, string Code, string SendTime, string Memark) 51 { 52 WeiXinQiYeHelp objWeiXinQiYeHelp = new WeiXinQiYeHelp(); 53 //objWeiXinQiYeHelp.SendNewMess("4289", "", "错误日志17", "openId:" + LinkURL + "|" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")); 54 55 string TemplateID = "tPzeIFp_tv7SD936k39s66-5iGeLbZ1084faTDk6gW4"; 56 string[] appID_appsecret = ConfigHelper.GetConfigString("appID_appsecret").Split('ζ'); 57 string Token = GetAccess_token(appID_appsecret[0], appID_appsecret[1]); 58 59 //objWeiXinQiYeHelp.SendNewMess("4289", "", "错误日志18", "openId:" + Token + "|" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")); 60 string postData = "{ \"touser\":\"" + ToOpenID + "\"," 61 + "\"template_id\":\"" + TemplateID + "\","; 62 if (!string.IsNullOrEmpty(LinkURL)) 63 { 64 postData += "\"url\":\"" + LinkURL + "\","; 65 } 66 postData += "\"topcolor\":\"#FF0000\"," 67 + "\"data\":{" + 68 "\"first\":{\"value\":\"" + TopMess + "\"}," + 69 "\"keyword1\":{\"value\":\"" + Code + "\"}," + 70 "\"keyword2\":{\"value\":\"" + SendTime + "\"}," + 71 "\"remark\":{\"value\":\"" + Memark + "\"}" 72 + "}" 73 + "}"; 74 75 //objWeiXinQiYeHelp.SendNewMess("4289", "", "错误日志19", "openId:" + postData + "|" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")); 76 string ReturnMess = postResponse("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + Token, postData); 77 //objWeiXinQiYeHelp.SendNewMess("4289", "", "错误日志20", "openId:" + ReturnMess + "|" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")); 78 return ReturnMess; 79 } 80 81 82 /// <summary> 83 /// 发送vip消费信息 84 /// </summary> 85 /// <param name="ToOpenID"></param> 86 /// <param name="LinkURL"></param> 87 /// <param name="first"></param> 88 /// <param name="keyword1"></param> 89 /// <param name="keyword2"></param> 90 /// <param name="keyword3"></param> 91 /// <param name="Memark"></param> 92 /// <returns></returns> 93 public string SendShoppingList(string ToOpenID, string LinkURL, string first, string keyword1, string keyword2, string keyword3, string Memark) 94 { 95 96 WeiXinQiYeHelp objWeiXinQiYeHelp = new WeiXinQiYeHelp(); 97 string TemplateID = "b3tZ5g5QWOVIapv8qa7sdm4QQSDh1h3_NOi6LDgUGkU"; 98 string[] appID_appsecret = ConfigHelper.GetConfigString("appID_appsecret").Split('ζ'); 99 string Token = GetAccess_token(appID_appsecret[0], appID_appsecret[1]); 100 101 102 string postData = "{ \"touser\":\"" + ToOpenID + "\"," 103 + "\"template_id\":\"" + TemplateID + "\","; 104 if (!string.IsNullOrEmpty(LinkURL)) 105 { 106 postData += "\"url\":\"" + LinkURL + "\","; 107 } 108 postData += "\"topcolor\":\"#FF0000\"," 109 + "\"data\":{" + 110 "\"first\":{\"value\":\"" + first + "\"}," + 111 "\"keyword1\":{\"value\":\"" + keyword1 + "\"}," + 112 "\"keyword2\":{\"value\":\"" + keyword2 + "\"}," + 113 "\"keyword3\":{\"value\":\"" + keyword3 + "\"}," + 114 "\"remark\":{\"value\":\"" + Memark + "\"}" 115 + "}" 116 + "}"; 117 118 //objWeiXinQiYeHelp.SendNewMess("4289", "", "错误日志19", "openId:" + postData + "|" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")); 119 string ReturnMess = postResponse("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + Token, postData); 120 //objWeiXinQiYeHelp.SendNewMess("4289", "", "错误日志20", "openId:" + ReturnMess + "|" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")); 121 return ReturnMess; 122 123 124 } 125 /// <summary> 126 /// 发送微信文本消息 127 /// </summary> 128 /// <param name="ToOpenID">接收用户ID</param> 129 /// <param name="Mess">发送内容</param> 130 /// <returns></returns> 131 public string SendTextMess(string ToOpenID, string Mess) 132 { 133 //appIDζappsecret 134 string[] appID_appsecret = ConfigHelper.GetConfigString("appID_appsecret").Split('ζ'); 135 string Token = GetAccess_token(appID_appsecret[0], appID_appsecret[1]); 136 string postData = "{\"touser\":\"" + ToOpenID + "\",\"msgtype\":\"text\",\"text\":{\"content\":\"" + Mess + "\"}}"; 137 string ReturnMess = postResponse("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + Token, postData); 138 return ReturnMess; 139 } 140 141 /// <summary> 142 /// 发送验证码消息 143 /// </summary> 144 /// <param name="ToOpenID"></param> 145 /// <param name="LinkURL"></param> 146 /// <param name="TopMess"></param> 147 /// <param name="Code"></param> 148 /// <param name="SendTime"></param> 149 /// <param name="Memark"></param> 150 /// <returns></returns> 151 public string SendTemplateMess1(string ToOpenID, string LinkURL, string TopMess, string Code, string SendTime, string Memark) 152 { 153 string TemplateID = "hDEyGOgszHwAKnVAjS_O9Kndv3YBsOaTINM3Y-kmJVM"; 154 string[] appID_appsecret = ConfigHelper.GetConfigString("appID_appsecret").Split('ζ'); 155 string Token = GetAccess_token(appID_appsecret[0], appID_appsecret[1]); 156 string postData = "{ \"touser\":\"" + ToOpenID + "\"," 157 + "\"template_id\":\"" + TemplateID + "\","; 158 if (!string.IsNullOrEmpty(LinkURL)) 159 { 160 postData += "\"url\":\"" + LinkURL + "\","; 161 } 162 postData += "\"topcolor\":\"#FF0000\"," 163 + "\"data\":{" + 164 "\"first\":{\"value\":\"" + TopMess + "\"}," + 165 "\"keyword1\":{\"value\":\"" + Code + "\"}," + 166 "\"keyword2\":{\"value\":\"" + SendTime + "\"}," + 167 "\"remark\":{\"value\":\"" + Memark + "\"}" 168 + "}" 169 + "}"; 170 string ReturnMess = postResponse("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + Token, postData); 171 return ReturnMess; 172 } 173 /// <summary> 174 /// 接收post数据 175 /// </summary> 176 /// <returns></returns> 177 public T getPostInput<T>(T obj) 178 { 179 StringBuilder log = new StringBuilder(); 180 string res = ""; 181 try 182 { 183 System.IO.Stream s = HttpContext.Current.Request.InputStream; 184 int count = 0; 185 byte[] buffer = new byte[10240]; 186 StringBuilder builder = new StringBuilder(); 187 while ((count = s.Read(buffer, 0, 10240)) > 0) 188 { 189 builder.Append(Encoding.UTF8.GetString(buffer, 0, count)); 190 } 191 s.Flush(); 192 s.Close(); 193 s.Dispose(); 194 log.Append("微信返回的消息:" + builder); 195 res = builder.ToString(); 196 obj = JSONHelper.JsonStrToT<T>(res); 197 return obj; 198 } 199 catch (Exception ex) 200 { 201 log.Append("ex:" + ex.ToString()); 202 203 return obj; 204 } 205 finally 206 { 207 //Common.PageValidate.WriteFile(log.ToString()); 208 } 209 } 210 /// <summary> 211 /// 发送日结消息 212 /// </summary> 213 /// <param name="ToOpenID"></param> 214 /// <param name="LinkURL"></param> 215 /// <param name="TopMess"></param> 216 /// <param name="Code"></param> 217 /// <param name="SendTime"></param> 218 /// <param name="Memark"></param> 219 /// <returns></returns> 220 public string SendTemplateMess2(string ToOpenID, string LinkURL, string first, string keyword1, string keyword2, string remark) 221 { 222 string TemplateID = "XPV1mNWCN9Jx-wHWDf8Vjw9gbxZ0wcpMRl25TlSAD8U"; 223 string[] appID_appsecret = ConfigHelper.GetConfigString("appID_appsecret").Split('ζ'); 224 string Token = GetAccess_token(appID_appsecret[0], appID_appsecret[1]); 225 string postData = "{ \"touser\":\"" + ToOpenID + "\"," 226 + "\"template_id\":\"" + TemplateID + "\","; 227 if (!string.IsNullOrEmpty(LinkURL)) 228 { 229 postData += "\"url\":\"" + LinkURL + "\","; 230 } 231 postData += "\"topcolor\":\"#FF0000\"," 232 + "\"data\":{" + 233 "\"first\":{\"value\":\"" + first + "\"}," + 234 "\"keyword1\":{\"value\":\"" + keyword1 + "\"}," + 235 "\"keyword2\":{\"value\":\"" + keyword2 + "\"}," + 236 "\"remark\":{\"value\":\"" + remark + "\"}" 237 + "}" 238 + "}"; 239 string ReturnMess = postResponse("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + Token, postData); 240 return ReturnMess; 241 } 242 243 244 245 /// <summary> 246 /// 接收post数据 247 /// </summary> 248 /// <returns></returns> 249 public string getPostInput() 250 { 251 StringBuilder log = new StringBuilder(); 252 string res = ""; 253 try 254 { 255 System.IO.Stream s = HttpContext.Current.Request.InputStream; 256 int count = 0; 257 byte[] buffer = new byte[10240]; 258 StringBuilder builder = new StringBuilder(); 259 while ((count = s.Read(buffer, 0, 10240)) > 0) 260 { 261 builder.Append(Encoding.UTF8.GetString(buffer, 0, count)); 262 } 263 s.Flush(); 264 s.Close(); 265 s.Dispose(); 266 log.Append("微信返回的消息:" + builder); 267 res = builder.ToString(); 268 return res; 269 } 270 catch (Exception ex) 271 { 272 log.Append("ex:" + ex.ToString()); 273 return ""; 274 } 275 finally 276 { 277 //Common.PageValidate.WriteFile(log.ToString()); 278 } 279 } 280 281 /// <summary> 282 /// post请求 283 /// </summary> 284 /// <param name="url"></param> 285 /// <returns></returns> 286 public string postResponse(string url, string postData) 287 { 288 try 289 { 290 byte[] b = System.Text.Encoding.UTF8.GetBytes(postData); 291 StringBuilder content = new StringBuilder(); 292 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 293 request.Method = "Post"; 294 request.ContentLength = b.Length; 295 using (Stream stream = request.GetRequestStream()) 296 { 297 stream.Write(b, 0, b.Length); 298 } 299 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 300 Stream responseStream = response.GetResponseStream(); 301 StreamReader sReader = new StreamReader(responseStream); 302 Char[] sReaderBuffer = new Char[2560]; 303 int count = sReader.Read(sReaderBuffer, 0, 2560); 304 while (count > 0) 305 { 306 String tempStr = new String(sReaderBuffer, 0, count); 307 content.Append(tempStr); 308 count = sReader.Read(sReaderBuffer, 0, 2560); 309 } 310 sReader.Close(); 311 return content.ToString(); 312 } 313 catch 314 { 315 return ""; 316 } 317 } 318 319 /// <summary> 320 /// get请求 321 /// </summary> 322 /// <param name="url"></param> 323 /// <returns></returns> 324 public string getResponse(string url) 325 { 326 try 327 { 328 StringBuilder content = new StringBuilder(); 329 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 330 request.Method = "GET"; 331 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 332 Stream responseStream = response.GetResponseStream(); 333 StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")); 334 Char[] sReaderBuffer = new Char[2560]; 335 int count = sReader.Read(sReaderBuffer, 0, 2560); 336 while (count > 0) 337 { 338 String tempStr = new String(sReaderBuffer, 0, count); 339 content.Append(tempStr); 340 count = sReader.Read(sReaderBuffer, 0, 2560); 341 } 342 sReader.Close(); 343 return content.ToString(); 344 } 345 catch 346 { 347 return ""; 348 } 349 } 350 351 352 /// <summary> 353 /// post请求 354 /// </summary> 355 /// <param name="url"></param> 356 /// <returns></returns> 357 public string postResponse<T>(string url, T obj) 358 { 359 try 360 { 361 string postData = JSONHelper.ToJSON(obj); 362 byte[] b = System.Text.Encoding.UTF8.GetBytes(postData); 363 StringBuilder content = new StringBuilder(); 364 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 365 request.Method = "Post"; 366 request.ContentLength = b.Length; 367 using (Stream stream = request.GetRequestStream()) 368 { 369 stream.Write(b, 0, b.Length); 370 } 371 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 372 Stream responseStream = response.GetResponseStream(); 373 StreamReader sReader = new StreamReader(responseStream); 374 Char[] sReaderBuffer = new Char[2560]; 375 int count = sReader.Read(sReaderBuffer, 0, 2560); 376 while (count > 0) 377 { 378 String tempStr = new String(sReaderBuffer, 0, count); 379 content.Append(tempStr); 380 count = sReader.Read(sReaderBuffer, 0, 2560); 381 } 382 sReader.Close(); 383 return content.ToString(); 384 } 385 catch 386 { 387 return ""; 388 } 389 } 390 391 392 /// <summary> 393 /// 调用微信接口获取带参数永久二维码的ticket 394 /// </summary> 395 /// <param name="appid"></param> 396 /// <param name="appsecret"></param> 397 /// <param name="orderNo"></param> 398 /// <returns></returns> 399 public string GetQrcodeYJ(string appid, string appsecret, string orderNo) 400 { 401 string QrcodeUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={0}";//WxQrcodeAPI接口 402 string AccessToken = GetAccess_token(appid, appsecret);//拉取AccessToken 403 QrcodeUrl = string.Format(QrcodeUrl, AccessToken); 404 string PostJson ="{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \""+orderNo+"\"}}}"; 405 string ReText = postResponse(QrcodeUrl, PostJson);//post提交 406 return ReText; 407 } 408 409 /// 410 411 /// 调用微信接口获取带参数临时二维码的ticket 412 /// 使用方法:https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET 413 ///二维码带的参数 414 /// json:ticket:换取二维码的凭证,expire_seconds:凭证有效时间,url:二维码解析后的地址。此处返回ticket 否则返回错误码 415 public string GetQrcode(string appid, string appsecret, string scene_str) 416 { 417 string QrcodeUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={0}";//WxQrcodeAPI接口 418 string AccessToken = GetAccess_token(appid, appsecret);//拉取AccessToken 419 QrcodeUrl = string.Format(QrcodeUrl, AccessToken); 420 string PostJson = "{\"expire_seconds\": 1800, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": " + scene_str + "}}}"; 421 string ReText = postResponse(QrcodeUrl, PostJson);//此处省略了 WebRequestPostOrGet即为WebHttpRequest发送Post请求 422 return ReText; 423 } 424 425 426 /// <summary> 427 /// 获取微信带参数的二维码图片 428 /// </summary> 429 /// <param name="ticket">票</param> 430 /// <param name="saveSrc">要保存的地址</param> 431 /// <returns></returns> 432 public bool GetCodePic(string ticket,string saveSrc) 433 { 434 string QrcodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;//WxQrcodeAPI接口 435 return ImageAction.DownloadPicture(QrcodeUrl, saveSrc); 436 437 } 438 439 /// <summary> 440 /// 获取随机数 441 /// </summary> 442 /// <param name="min"></param> 443 /// <param name="max"></param> 444 /// <returns></returns> 445 public static int GetRandNum(int min, int max) 446 { 447 Random r = new Random(Guid.NewGuid().GetHashCode()); 448 return r.Next(min, max); 449 } 450 451 #region 微信红包相关 452 453 /// <summary> 454 /// 调用微信支付接口前处理数据,包括sign验证等 455 /// </summary> 456 /// <param name="payForWeiXin"></param> 457 /// <returns></returns> 458 public string DoDataForPayWeiXin(PayWeiXin payForWeiXin) 459 { 460 #region 处理nonce_str随机字符串,不长于 32 位(本程序生成长度为16位的) 461 string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 462 payForWeiXin.nonce_str = RandomStr(str, 16); 463 #endregion 464 465 #region 商户信息从config文件中读取 466 //商户支付密钥key 467 string key = ConfigurationManager.AppSettings["OwnerKey"].ToString(); 468 //商户号 469 payForWeiXin.mch_id = ConfigurationManager.AppSettings["mch_id"].ToString(); 470 //商户 appid 471 payForWeiXin.wxappid = ConfigurationManager.AppSettings["wxappid"].ToString(); 472 //红包収送者名称 473 payForWeiXin.send_name = ConfigurationManager.AppSettings["send_name"].ToString(); 474 //红包収放总人数 475 payForWeiXin.total_num = int.Parse(ConfigurationManager.AppSettings["total_num"].ToString()); 476 //红包祝福诧 477 payForWeiXin.wishing = ConfigurationManager.AppSettings["wishing"].ToString(); 478 //活劢名称 479 payForWeiXin.act_name = ConfigurationManager.AppSettings["act_name"].ToString(); 480 //备注信息 481 payForWeiXin.remark = ConfigurationManager.AppSettings["remark"].ToString(); 482 483 //调用接口的机器 Ip 地址 484 payForWeiXin.client_ip = ConfigurationManager.AppSettings["client_ip"].ToString(); 485 #endregion 486 487 #region 订单信息 488 //生成订单号组成: mch_id+yyyymmdd+10 位一天内不能重复的数字 489 //生成10位不重复的数字 490 string num = "0123456789"; 491 string randomNum = RandomStr(num, 10); 492 payForWeiXin.mch_billno = payForWeiXin.mch_billno + System.DateTime.Now.ToString("yyyyMMdd") + randomNum; 493 #endregion 494 495 string postData = @"<xml> 496 <mch_billno>{0}</mch_billno> 497 <mch_id>{1}</mch_id> 498 <wxappid>{2}</wxappid> 499 <send_name>{3}</send_name> 500 <re_openid>{4}</re_openid> 501 <total_amount>{5}</total_amount> 502 <total_num>{6}</total_num> 503 <wishing>{7}</wishing> 504 <client_ip>{8}</client_ip> 505 <act_name>{9}</act_name> 506 <remark>{10}</remark> 507 <nonce_str>{11}</nonce_str>"; 508 postData = string.Format(postData, 509 payForWeiXin.mch_billno, 510 payForWeiXin.mch_id, 511 payForWeiXin.wxappid, 512 payForWeiXin.send_name, 513 payForWeiXin.re_openid, 514 payForWeiXin.total_amount, 515 payForWeiXin.total_num, 516 payForWeiXin.wishing, 517 payForWeiXin.client_ip, 518 payForWeiXin.act_name, 519 payForWeiXin.remark, 520 payForWeiXin.nonce_str 521 ); 522 523 524 //原始传入参数 525 string[] signTemp = { "mch_billno=" + payForWeiXin.mch_billno, "mch_id=" + payForWeiXin.mch_id, "wxappid=" + payForWeiXin.wxappid, "send_name=" + payForWeiXin.send_name, "re_openid=" + payForWeiXin.re_openid, "total_amount=" + payForWeiXin.total_amount, "total_num=" + payForWeiXin.total_num, "wishing=" + payForWeiXin.wishing, "client_ip=" + payForWeiXin.client_ip, "act_name=" + payForWeiXin.act_name,"remark=" + payForWeiXin.remark, "nonce_str=" + payForWeiXin.nonce_str }; 526 527 List<string> signList = signTemp.ToList(); 528 529 #region 处理支付签名 530 //对signList按照ASCII码从小到大的顺序排序 531 signList.Sort(); 532 533 string signOld = string.Empty; 534 string payForWeiXinOld = string.Empty; 535 int i = 0; 536 foreach (string temp in signList) 537 { 538 signOld += temp + "&"; 539 i++; 540 } 541 signOld = signOld.Substring(0, signOld.Length - 1); 542 //拼接Key 543 signOld += "&key=" + key; 544 //处理支付签名 545 payForWeiXin.sign = Encrypt(signOld).ToUpper(); 546 #endregion 547 postData += "<sign>{0}</sign></xml>"; 548 postData = string.Format(postData, payForWeiXin.sign); 549 return postData; 550 } 551 552 553 554 public string RandomStr(string str, int Length) 555 { 556 string result = string.Empty; 557 Random rd = new Random(); 558 for (int i = 0; i < Length; i++) 559 { 560 result += str[rd.Next(str.Length)]; 561 } 562 return result; 563 } 564 565 /// <summary> 566 /// Md5加密 567 /// </summary> 568 /// <param name="s"></param> 569 /// <returns></returns> 570 public static String Encrypt(String s) 571 { 572 MD5 md5 = new MD5CryptoServiceProvider(); 573 byte[] bytes = System.Text.Encoding.UTF8.GetBytes(s); 574 bytes = md5.ComputeHash(bytes); 575 md5.Clear(); 576 string ret = ""; 577 for (int i = 0; i < bytes.Length; i++) 578 { 579 ret += Convert.ToString(bytes[i], 16).PadLeft(2, '0'); 580 } 581 return ret.PadLeft(32, '0'); 582 } 583 584 585 /// <summary> 586 /// 调用微信支付接口 587 /// </summary> 588 /// <param name="payForWeiXin"></param> 589 /// <returns></returns> 590 public string PayForWeiXin(string postData) 591 { 592 string result = string.Empty; 593 try 594 { 595 result = PostPage("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack", postData); 596 } 597 catch (Exception ex) 598 { 599 600 } 601 return result; 602 } 603 604 605 /// <summary> 606 /// post微信请求 607 /// </summary> 608 /// <param name="posturl"></param> 609 /// <param name="postData"></param> 610 /// <returns></returns> 611 public string PostPage(string posturl, string postData) 612 { 613 Stream outstream = null; 614 Stream instream = null; 615 StreamReader sr = null; 616 HttpWebResponse response = null; 617 HttpWebRequest request = null; 618 Encoding encoding = Encoding.UTF8; 619 byte[] data = encoding.GetBytes(postData); 620 // 准备请求... 621 try 622 { 623 //CerPath证书路径 624 string certPath = ConfigurationManager.AppSettings["certPath"].ToString(); 625 certPath = System.Web.HttpContext.Current.Server.MapPath(certPath); 626 //证书密码 627 string password = ConfigurationManager.AppSettings["password"].ToString(); 628 X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certPath, password, X509KeyStorageFlags.MachineKeySet); 629 630 // 设置参数 631 request = WebRequest.Create(posturl) as HttpWebRequest; 632 CookieContainer cookieContainer = new CookieContainer(); 633 request.CookieContainer = cookieContainer; 634 request.AllowAutoRedirect = true; 635 request.Method = "POST"; 636 request.ContentType = "text/xml"; 637 request.ContentLength = data.Length; 638 request.ClientCertificates.Add(cert); 639 outstream = request.GetRequestStream(); 640 outstream.Write(data, 0, data.Length); 641 outstream.Close(); 642 //发送请求并获取相应回应数据 643 response = request.GetResponse() as HttpWebResponse; 644 //直到request.GetResponse()程序才开始向目标网页发送Post请求 645 instream = response.GetResponseStream(); 646 sr = new StreamReader(instream, encoding); 647 //返回结果网页(html)代码 648 string content = sr.ReadToEnd(); 649 string err = string.Empty; 650 return content; 651 652 } 653 catch (Exception ex) 654 { 655 string err = ex.Message; 656 return string.Empty; 657 } 658 } 659 #endregion 660 661 /// <summary> 662 /// 模拟微信关注 663 /// </summary> 664 public string FocusLike() 665 { 666 string postData = @"<xml><ToUserName>{0}</ToUserName> 667 <FromUserName>{1}</FromUserName> 668 <CreateTime>{2}</CreateTime> 669 <MsgType>{3}</MsgType> 670 <Event>{4}</Event> 671 <EventKey>{5}</EventKey> 672 <Ticket>{6}</Ticket> 673 </xml>"; 674 postData = string.Format(postData, 675 "gh_0c33237af015", 676 "okehNt44afCOnburT5b7dXHivlSc", 677 "1469152031", 678 "event", 679 "SCAN", 680 "S0064216072100364", 681 "1234" 682 ); 683 684 return PostPage1("http://localhost:33700/api/JDFWXService/Service",postData); 685 686 } 687 688 /// <summary> 689 /// post微信请求 690 /// </summary> 691 /// <param name="posturl"></param> 692 /// <param name="postData"></param> 693 /// <returns></returns> 694 public string PostPage1(string posturl, string postData) 695 { 696 Stream outstream = null; 697 Stream instream = null; 698 StreamReader sr = null; 699 HttpWebResponse response = null; 700 HttpWebRequest request = null; 701 Encoding encoding = Encoding.UTF8; 702 byte[] data = encoding.GetBytes(postData); 703 // 准备请求... 704 try 705 { 706 // 设置参数 707 request = WebRequest.Create(posturl) as HttpWebRequest; 708 CookieContainer cookieContainer = new CookieContainer(); 709 request.CookieContainer = cookieContainer; 710 request.AllowAutoRedirect = true; 711 request.Method = "POST"; 712 request.ContentType = "text/xml"; 713 request.ContentLength = data.Length; 714 outstream = request.GetRequestStream(); 715 outstream.Write(data, 0, data.Length); 716 outstream.Close(); 717 //发送请求并获取相应回应数据 718 response = request.GetResponse() as HttpWebResponse; 719 //直到request.GetResponse()程序才开始向目标网页发送Post请求 720 instream = response.GetResponseStream(); 721 sr = new StreamReader(instream, encoding); 722 //返回结果网页(html)代码 723 string content = sr.ReadToEnd(); 724 string err = string.Empty; 725 return content; 726 727 } 728 catch (Exception ex) 729 { 730 string err = ex.Message; 731 return string.Empty; 732 } 733 } 734 735 736 } 737 }
微信红包功能可以参考:csdn的实例下载。
四、效果
四、开发总结
1.这个功能应该是连接客户比较实用的功能,提高客户的依赖度。
2.开发时调试比较麻烦,我的方法是使用微信服务号的api发送错误日志到我的微信上,另一个方法是自己模拟微信的回调事件(这个方法很好,可以直接在vs中调试)。
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
下一篇:Redis缓存公共方法类
- asp控件和html控件的概念区别 2020-03-09
- .NET下通过HttpListener实现简单的Http服务 2020-02-27
- .net微信服务号发送红包 2020-02-27
- C#利用服务器实现客户端之间通信 2020-01-20
- ASP.NET Core Razor 页面路由详解 2019-12-08
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash