如何使用.net构建微信服务号发送红包
发表于:2025-02-04 作者:千家信息网编辑
千家信息网最后更新 2025年02月04日,这期内容当中小编将会给大家带来有关如何使用.net构建微信服务号发送红包,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。注:需要开通微信支付的服务号!//跳转微信登录
千家信息网最后更新 2025年02月04日如何使用.net构建微信服务号发送红包
这期内容当中小编将会给大家带来有关如何使用.net构建微信服务号发送红包,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
注:需要开通微信支付的服务号!
//跳转微信登录页面public ActionResult Index(){ ViewBag.url = "https://open.weixin.qq.com/connect/oauth3/authorize?appid=" + {服务号appid} + "&redirect_uri=http%3A%2F%2F" + {微信重定向域名(填写程序域名,例如:www.xxxx.com)} + "%2F"+{程序控制器名,例如:Home}+"%2F"+{程序Action名,例如:RedirectWeChat}+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; return View();}//获取accesstoken(访问微信接口需要)public static string accesstoken(string WeChatWxAppId, string WeChatWxAppSecret){ string strJson = HttpRequestUtil.RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", WeChatWxAppId, WeChatWxAppSecret)); if (strJson.IndexOf("errcode") == -1) { return GetJsonValue(strJson, "access_token"); } else { return ""; }}//解析jsonpublic static string GetJsonValue(string jsonStr, string key){ string result = string.Empty; if (!string.IsNullOrEmpty(jsonStr)) { key = "\"" + key.Trim('"') + "\""; int index = jsonStr.IndexOf(key) + key.Length + 1; if (index > key.Length + 1) { //先截逗号,若是最后一个,截"}"号,取最小值 int end = jsonStr.IndexOf(',', index); if (end == -1) { end = jsonStr.IndexOf('}', index); } result = jsonStr.Substring(index, end - index); result = result.Trim(new char[] { '"', ' ', '\'' }); //过滤引号或空格 } } return result;}//请求urlpublic static string RequestUrl(string url, string method="post"){ // 设置参数 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = method; request.ContentType = "text/html"; request.Headers.Add("charset", "utf-8"); //发送请求并获取相应回应数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream responseStream = response.GetResponseStream(); StreamReader sr = new StreamReader(responseStream, Encoding.UTF8); //返回结果网页(html)代码 string content = sr.ReadToEnd(); return content;}//接收微信返回code//接收微信数据获取用户信息public ActionResult RedirectWeChat(string code, string state){ if (string.IsNullOrEmpty(code)) { return Content("您拒绝了授权!"); } string access_token = accesstoken(微信AppId, 微信AppSecret); string st = "https://api.weixin.qq.com/sns/oauth3/access_token?appid=" + 微信AppId + "&secret=" + 微信AppSecret + "&code=" + code + "&grant_type=authorization_code"; string data = RequestUrl(st);//拿到用户openidstring openid=GetJsonValue(data, "openid");//获取用户其他信息 string url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN"; data = RequestUrl(url);string subscribe=GetJsonValue(data, "subscribe"); if (subscribe == "0") { ///未关注 return RedirectToAction(""); } return RedirectToAction("");}//发送红包Actionpublic ActionResult HB(){ string openid = "";//用户openid string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"; string orderNo = 商户号 + DateTime.Now.ToString("yyyymmdd")+"随机10位数字";//商户订单号 组成:mch_id+yyyymmdd+10位一天内不能重复的数字。 string Code = ""//32为随机字符串; string key="key=" + "";//支付密钥(在商户平台设置32为字符串) Dictionarydata = new Dictionary (); data.Add("act_name", "");//活动名称 data.Add("client_ip", "192.168.1.1");//Ip地址 data.Add("mch_billno", orderNo);//商户订单号 组成:mch_id+yyyymmdd+10位一天内不能重复的数字。 data.Add("mch_id", "");//商户号 data.Add("nonce_str", Code);//随机字符串 data.Add("re_openid", openid);//用户openid data.Add("remark", "");//备注 data.Add("send_name","");//商户名称 data.Add("total_amount", "100");//付款金额 单位分 data.Add("total_num", "1");//红包发放总人数 data.Add("wishing", "恭喜发财");//红包祝福语 data.Add("wxappid", );//公众账号appid string xml = GetXML(data, key);//签名+拼接xml string str=PostWebRequests(url, xml);//微信返回xml err_code=SUCCESS 就是成功 return View(""); }//发送红包(MD5签名+拼接XML)public static string GetXML(Dictionary data,string paykey){ string retStr; MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider(); var data1=from d in data orderby d.Key select d; string data2 = ""; string XML = " "; foreach (var item in data1) { //空值不参与签名 if (item.Value + "" != "") { data2 += item.Key +"="+ item.Value + "&"; } XML += "<" + item.Key + ">" + item.Value+""+ "" + item.Key + ">"; } data2 += paykey; //创建md5对象 byte[] inputBye; byte[] outputBye; //使用GB2312编码方式把字符串转化为字节数组. try { inputBye = Encoding.UTF8.GetBytes(data2); } catch { inputBye = Encoding.GetEncoding("GB2312").GetBytes(data2); } outputBye = m5.ComputeHash(inputBye); retStr = System.BitConverter.ToString(outputBye); retStr = retStr.Replace("-", "").ToUpper(); XML += " "; return XML;}//发送红包请求Post方法public static string PostWebRequests(string postUrl, string menuInfo){ string returnValue = string.Empty; try { Encoding encoding = Encoding.UTF8; byte[] bytes = encoding.GetBytes(menuInfo); string cert = @"E:\cdcert\apiclient_cert.p12";//支付证书路径 string password = "1212121";//支付证书密码 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); X509Certificate cer = new X509Certificate(cert, password, X509KeyStorageFlags.MachineKeySet); HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(postUrl); webrequest.ClientCertificates.Add(cer); webrequest.Method = "post"; webrequest.ContentLength = bytes.Length; webrequest.GetRequestStream().Write(bytes, 0, bytes.Length); HttpWebResponse webreponse = (HttpWebResponse)webrequest.GetResponse(); Stream stream = webreponse.GetResponseStream(); string resp = string.Empty; using (StreamReader reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } catch (Exception ex) { return ""; }}" + retStr + " ";//签名 XML += "
上述就是小编为大家分享的如何使用.net构建微信服务号发送红包了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注行业资讯频道。
红包
商户
用户
服务
字符
字符串
程序
支付
数字
信息
内容
名称
域名
就是
数据
网页
订单
订单号
证书
分析
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
服务器怎么装系统教程视频
小提案建议表网络安全怎么写
公共网络安全报告
服务器系统id灯怎么看
软件开发比硬件开发难
游戏服务器负载均衡
数据库查询李勇所选课程的成绩
上海嵌入式软件开发哪家实惠
湖北浪潮服务器续保维护云空间
学生网络安全学习感受300字
网络技术经理考核指标
德仁顾问咨询数据库
g7服务器怎么升级大硬盘
excel有数据库打开全是空白
教学软件开发需要的知识结构
网客联盟软件开发 牛牛
成语翻译软件开发
以色列网络安全建设
魔兽世界 pve服务器
主流的软件开发或项目管理工具
win服务器2008激活
华为美国区网络安全官
MGI数据库怎么使用
服务器安全狗退出
图片非关系型数据库
珠海金融软件开发联系方式
信息通信网络技术员
网络安全零基础ccie
贵广网络技术岗位待遇
数据库表数据自己不断减少