This article for you to share the. NET micro-letter red envelopes sent code for your reference, the specific content as follows
Note: need to open the service number of micro-letter payment!
Jump micro-Letter Login page public ActionResult Index () {viewbag.url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + { Service number AppID} + "&redirect_uri=http%3a%2f%2f" + {micro-letter Redirect Domain name (fill in the program domain name, for example: www.xxxx.com)} + "%2F" +{program controller name, for example: home}+ "%2f" +{ Program action name, for example: redirectwechat}+ "&response_type=code&scope=snsapi_userinfo&state=state#wechat_
Redirect ";
return View (); //Get Accesstoken (required to access the micro-communication interface) public static string Accesstoken (String wechatwxappid, String wechatwxappsecret) {String St Rjson = 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 ""; }//Parse 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) {//First truncate comma, if last, truncate "}" number, take minimum int end = Jsonstr.indexof (', ', index);
if (end = = 1) {end = Jsonstr.indexof ('} ', index);
result = jsonstr.substring (index, End-index); result = result. Trim (new char[] {' "', ', ', '} '});
Filter quotes or spaces} return result; //Request URL public static string Requesturl (string url, String method= "post") {//set parameter HttpWebRequest request = Webreque St.
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"); Send request and get corresponding response data httpwebresponse response = Request.
GetResponse () as HttpWebResponse; Until request. The GetResponse () program only starts sending post requests to the target Web page Stream responsestream = response.
GetResponseStream ();
StreamReader sr = new StreamReader (Responsestream, Encoding.UTF8); return resultsWeb page (HTML) code string content = Sr.
ReadToEnd ();
return content; ///Receive micro-letter return code//Receive micro-data get user Information public ActionResult redirectwechat (string code, string state) {if (string). IsNullOrEmpty (code) {return Content ("You denied authorization!")
");
String access_token = Accesstoken (micro-letter AppID, micro-letter Appsecret); String st = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + micro-letter AppID + "&secret=" + micro-letter Appsecret + "&c
Ode= "+ code +" &grant_type=authorization_code ";
String data = Requesturl (ST);
Get user OpenID string Openid=getjsonvalue (data, "OpenID"); Get user additional information string url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + Access_token + "&openid=" + op
Enid + "&LANG=ZH_CN";
data = Requesturl (URL);
String Subscribe=getjsonvalue (data, "subscribe");
if (subscribe = = "0") {///is not concerned about return Redirecttoaction ("");
Return Redirecttoaction ("");} Send Red envelope action public ActionResult HB () {String OpenID = "";/user OpenID string url = "Https://api.mch.weixin.qq.com/mmpaym KttransfErs/sendredpack ";
String OrderNo = Merchant number + DateTime.Now.ToString ("YYYYMMDD") + "random 10 digits";//Merchant Order number composition: mch_id+yyyymmdd+10 digits that cannot be duplicated in one day. String Code = ""//32 is a random string; String key= "key=" + "";//Payment key (on merchant platform set 32 is String) dictionary<string, string> data = new dictionary<string, String> ;(); Data. ADD ("Act_name", "");//Activity name data. Add ("Client_ip", "192.168.1.1");//ip address data.
ADD ("Mch_billno", orderNo);//Merchant Order Number: Mch_id+yyyymmdd+10 number that cannot be duplicated in one day. Data. ADD ("mch_id", "");//merchant Number data. ADD ("Nonce_str", Code);//random string data. ADD ("Re_openid", OpenID);//user OpenID data. ADD ("Remark", "");//Memo data. ADD ("Send_name", "");//merchant name data. ADD ("Total_amount", "100");//payment amount per unit data. ADD ("Total_num", "1"), and/or red envelopes issued the total number of data. ADD ("Wishing", "congratulate the rich");//Red Envelope blessing language data. ADD ("Wxappid",);/Public account AppID String xml = GetXML (data, key);//signature + concatenation XML string str=postwebrequests (URL, XML);//micro-letter return XML
Err_code=success is the successful return View (""); //Send Red envelopes (MD5 signature + stitching XML) public static string GetXML (Dictionary<string, string> data,string Paykey) {string retstr;
MD5CryptoServiceProvider M5 = new MD5CryptoServiceProvider ();
var data1=from d in data by D.key Select D;
String data2 = "";
String XML = "<xml>"; foreach (var item in data1) {//null value does not participate in signing if (item. Value + ""!= "") {data2 + + item. Key + "=" + Item.
Value + "&"; XML = + "<" + Item. Key + ">" + Item. value+ "" + "</" + item.
Key + ">";
} data2 + = Paykey;
Create MD5 object byte[] Inputbye;
Byte[] Outputbye;
Converts a string to a byte array using the GB2312 encoding method.
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>";//Signed XML + + "</xml>";
return XML; //Send red Envelope request Post method 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";//Payment certificate path string password = "1212121";//Payment Certificate Password Servicepointmanager.serve
Rcertificatevalidationcallback = 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 ";
}
}
Here is the micro-credit development of the official documents
1. "Micro-credit Payment" public number payment developer documentation
2. Micro-Credit Open platform
3. Enterprise Developer Interface Documentation
4. Micro-trust public Platform Developer Documentation
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.