.net微信服务号发送红包
本文实例为大家分享了.net微信红包发送代码,供大家参考,具体内容如下
注:需要开通微信支付的服务号!
//跳转微信登录页面 publicActionResultIndex() { ViewBag.url="https://open.weixin.qq.com/connect/oauth2/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"; returnView(); } //获取accesstoken(访问微信接口需要) publicstaticstringaccesstoken(stringWeChatWxAppId,stringWeChatWxAppSecret) { stringstrJson=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) { returnGetJsonValue(strJson,"access_token"); } else { return""; } } //解析json publicstaticstringGetJsonValue(stringjsonStr,stringkey) { stringresult=string.Empty; if(!string.IsNullOrEmpty(jsonStr)) { key="\""+key.Trim('"')+"\""; intindex=jsonStr.IndexOf(key)+key.Length+1; if(index>key.Length+1) { //先截逗号,若是最后一个,截“}”号,取最小值 intend=jsonStr.IndexOf(',',index); if(end==-1) { end=jsonStr.IndexOf('}',index); } result=jsonStr.Substring(index,end-index); result=result.Trim(newchar[]{'"','','\''});//过滤引号或空格 } } returnresult; } //请求url publicstaticstringRequestUrl(stringurl,stringmethod="post") { //设置参数 HttpWebRequestrequest=WebRequest.Create(url)asHttpWebRequest; CookieContainercookieContainer=newCookieContainer(); request.CookieContainer=cookieContainer; request.AllowAutoRedirect=true; request.Method=method; request.ContentType="text/html"; request.Headers.Add("charset","utf-8"); //发送请求并获取相应回应数据 HttpWebResponseresponse=request.GetResponse()asHttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 StreamresponseStream=response.GetResponseStream(); StreamReadersr=newStreamReader(responseStream,Encoding.UTF8); //返回结果网页(html)代码 stringcontent=sr.ReadToEnd(); returncontent; } //接收微信返回code //接收微信数据获取用户信息 publicActionResultRedirectWeChat(stringcode,stringstate) { if(string.IsNullOrEmpty(code)) { returnContent("您拒绝了授权!"); } stringaccess_token=accesstoken(微信AppId,微信AppSecret); stringst="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+微信AppId+"&secret="+微信AppSecret+"&code="+code+"&grant_type=authorization_code"; stringdata=RequestUrl(st); //拿到用户openid stringopenid=GetJsonValue(data,"openid"); //获取用户其他信息 stringurl="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+openid+"&lang=zh_CN"; data=RequestUrl(url); stringsubscribe=GetJsonValue(data,"subscribe"); if(subscribe=="0") { ///未关注 returnRedirectToAction(""); } returnRedirectToAction(""); } //发送红包Action publicActionResultHB() { stringopenid="";//用户openid stringurl="https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"; stringorderNo=商户号+DateTime.Now.ToString("yyyymmdd")+"随机10位数字";//商户订单号组成:mch_id+yyyymmdd+10位一天内不能重复的数字。 stringCode=""//32为随机字符串;stringkey="key="+"";//支付密钥(在商户平台设置32为字符串) Dictionary<string,string>data=newDictionary<string,string>();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 stringxml=GetXML(data,key);//签名+拼接xml stringstr=PostWebRequests(url,xml);//微信返回xmlerr_code=SUCCESS就是成功 returnView(""); } //发送红包(MD5签名+拼接XML) publicstaticstringGetXML(Dictionary<string,string>data,stringpaykey) { stringretStr; MD5CryptoServiceProviderm5=newMD5CryptoServiceProvider(); vardata1=fromdindataorderbyd.Keyselectd; stringdata2=""; stringXML="<xml>"; foreach(varitemindata1) { //空值不参与签名 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+="<sign>"+retStr+"</sign>";//签名 XML+="</xml>"; returnXML; } //发送红包请求Post方法 publicstaticstringPostWebRequests(stringpostUrl,stringmenuInfo) { stringreturnValue=string.Empty; try { Encodingencoding=Encoding.UTF8; byte[]bytes=encoding.GetBytes(menuInfo); stringcert=@"E:\cdcert\apiclient_cert.p12";//支付证书路径 stringpassword="1212121";//支付证书密码 ServicePointManager.ServerCertificateValidationCallback=newRemoteCertificateValidationCallback(CheckValidationResult); X509Certificatecer=newX509Certificate(cert,password,X509KeyStorageFlags.MachineKeySet); HttpWebRequestwebrequest=(HttpWebRequest)HttpWebRequest.Create(postUrl); webrequest.ClientCertificates.Add(cer); webrequest.Method="post"; webrequest.ContentLength=bytes.Length; webrequest.GetRequestStream().Write(bytes,0,bytes.Length); HttpWebResponsewebreponse=(HttpWebResponse)webrequest.GetResponse(); Streamstream=webreponse.GetResponseStream(); stringresp=string.Empty; using(StreamReaderreader=newStreamReader(stream)) { returnreader.ReadToEnd(); } } catch(Exceptionex) { return""; } }
以下是微信开发官方相关文档
1.【微信支付】公众号支付开发者文档
2.微信开放平台
3.企业号开发者接口文档
4.微信公众平台开发者文档
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。