.net微信服務(wù)號(hào)發(fā)送紅包
本文實(shí)例為大家分享了.net微信紅包發(fā)送代碼,供大家參考,具體內(nèi)容如下
注:需要開通微信支付的服務(wù)號(hào)!
//跳轉(zhuǎn)微信登錄頁(yè)面
public ActionResult Index()
{
ViewBag.url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + {服務(wù)號(hào)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(訪問(wèn)微信接口需要)
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 "";
}
}
//解析json
public 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)
{
//先截逗號(hào),若是最后一個(gè),截“}”號(hào),取最小值
int end = jsonStr.IndexOf(',', index);
if (end == -1)
{
end = jsonStr.IndexOf('}', index);
}
result = jsonStr.Substring(index, end - index);
result = result.Trim(new char[] { '"', ' ', '\'' }); //過(guò)濾引號(hào)或空格
}
}
return result;
}
//請(qǐng)求url
public static string RequestUrl(string url, string method="post")
{
// 設(shè)置參數(shù)
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");
//發(fā)送請(qǐng)求并獲取相應(yīng)回應(yīng)數(shù)據(jù)
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才開始向目標(biāo)網(wǎng)頁(yè)發(fā)送Post請(qǐng)求
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
//返回結(jié)果網(wǎng)頁(yè)(html)代碼
string content = sr.ReadToEnd();
return content;
}
//接收微信返回code
//接收微信數(shù)據(jù)獲取用戶信息
public ActionResult RedirectWeChat(string code, string state)
{
if (string.IsNullOrEmpty(code))
{
return Content("您拒絕了授權(quán)!");
}
string access_token = accesstoken(微信AppId, 微信AppSecret);
string st = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + 微信AppId + "&secret=" + 微信AppSecret + "&code=" + code + "&grant_type=authorization_code";
string data = RequestUrl(st);
//拿到用戶openid
string 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")
{
///未關(guān)注
return RedirectToAction("");
}
return RedirectToAction("");
}
//發(fā)送紅包Action
public ActionResult HB()
{
string openid = "";//用戶openid
string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
string orderNo = 商戶號(hào) + DateTime.Now.ToString("yyyymmdd")+"隨機(jī)10位數(shù)字";//商戶訂單號(hào) 組成:mch_id+yyyymmdd+10位一天內(nèi)不能重復(fù)的數(shù)字。
string Code = ""http://32為隨機(jī)字符串; string key="key=" + "";//支付密鑰(在商戶平臺(tái)設(shè)置32為字符串)
Dictionary<string, string> data = new Dictionary<string, string>(); data.Add("act_name", "");//活動(dòng)名稱
data.Add("client_ip", "192.168.1.1");//Ip地址
data.Add("mch_billno", orderNo);//商戶訂單號(hào) 組成:mch_id+yyyymmdd+10位一天內(nèi)不能重復(fù)的數(shù)字。
data.Add("mch_id", "");//商戶號(hào)
data.Add("nonce_str", Code);//隨機(jī)字符串
data.Add("re_openid", openid);//用戶openid
data.Add("remark", "");//備注
data.Add("send_name","");//商戶名稱
data.Add("total_amount", "100");//付款金額 單位分
data.Add("total_num", "1");//紅包發(fā)放總?cè)藬?shù)
data.Add("wishing", "恭喜發(fā)財(cái)");//紅包祝福語(yǔ)
data.Add("wxappid", );//公眾賬號(hào)appid
string xml = GetXML(data, key);//簽名+拼接xml
string str=PostWebRequests(url, xml);//微信返回xml err_code=SUCCESS 就是成功
return View("");
}
//發(fā)送紅包(MD5簽名+拼接XML)
public static string GetXML(Dictionary<string, string> data,string paykey)
{
string retStr;
MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();
var data1=from d in data orderby d.Key select d;
string data2 = "";
string XML = "<xml>";
foreach (var item in data1)
{
//空值不參與簽名
if (item.Value + "" != "")
{
data2 += item.Key +"="+ item.Value + "&";
}
XML += "<" + item.Key + ">" + item.Value+""+ "</" + item.Key + ">";
}
data2 += paykey;
//創(chuàng)建md5對(duì)象
byte[] inputBye;
byte[] outputBye;
//使用GB2312編碼方式把字符串轉(zhuǎn)化為字節(jié)數(shù)組.
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>";
return XML;
}
//發(fā)送紅包請(qǐng)求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 "";
}
}
以下是微信開發(fā)官方相關(guān)文檔
1. 【微信支付】公眾號(hào)支付開發(fā)者文檔
2. 微信開放平臺(tái)
3.企業(yè)號(hào)開發(fā)者接口文檔
4.微信公眾平臺(tái)開發(fā)者文檔
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
asp.net 安全的截取指定長(zhǎng)度的html或者ubb字符串
在將html代碼輸出到頁(yè)面時(shí),有時(shí)候會(huì)需要截?cái)嘧址A糁付ㄩL(zhǎng)度的字符串,由于html中有些標(biāo)簽必須成對(duì)出現(xiàn),所以在截取html時(shí)需要特別注意,不能因?yàn)榻財(cái)鄦?wèn)題把頁(yè)面搞亂掉。2010-01-01
asp.net中c#自定義事件的實(shí)現(xiàn)方法詳解
這篇文章主要介紹了asp.net中c#自定義事件的實(shí)現(xiàn)方法,較為詳細(xì)的分析了自定義實(shí)現(xiàn)的各個(gè)步驟的具體實(shí)現(xiàn)思路與技巧,并給出了一個(gè)完整的實(shí)例總結(jié),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2014-12-12
ASP.NET GridView的Bootstrap分頁(yè)樣式
這篇文章主要為大家詳細(xì)介紹了ASP.NET GridView的Bootstrap分頁(yè)樣式,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-11-11
vs2017軟鏈接失效而導(dǎo)致無(wú)法進(jìn)入安裝界面的解決方法
這篇文章主要為大家詳細(xì)介紹了vs2017軟鏈接失效而導(dǎo)致無(wú)法進(jìn)入安裝界面的解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-09-09
asp.net實(shí)現(xiàn)的MVC跨數(shù)據(jù)庫(kù)多表聯(lián)合動(dòng)態(tài)條件查詢功能示例
這篇文章主要介紹了asp.net實(shí)現(xiàn)的MVC跨數(shù)據(jù)庫(kù)多表聯(lián)合動(dòng)態(tài)條件查詢功能,結(jié)合實(shí)例形式較為詳細(xì)分析了asp.net基于MVC架構(gòu)的跨數(shù)據(jù)庫(kù)多表聯(lián)合查詢功能實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-02-02
asp.net中簡(jiǎn)體轉(zhuǎn)繁體實(shí)現(xiàn)代碼
最近到了臺(tái)企,什么都要用繁體的。開發(fā)中也遇到了簡(jiǎn)繁體轉(zhuǎn)換的問(wèn)題。這里和朋友們分享一下用.net實(shí)現(xiàn)簡(jiǎn)繁體轉(zhuǎn)換的經(jīng)驗(yàn)。2010-03-03
ASP.NET數(shù)據(jù)庫(kù)存取圖片的方法
這篇文章主要為大家詳細(xì)介紹了ASP.NET數(shù)據(jù)庫(kù)如何存取圖片,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01

