In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you how to develop C# official account to send red packets to users, I believe most people do not know much about it, so share this article for your reference. I hope you will learn a lot after reading this article. Let's take a look at it!
A brief introduction to the red packet function:
1. When merchants call the interface, they give out red packets by specifying the object to be sent and the amount they send. This way allows merchants to flexibly apply to a variety of rich activity scenarios.
2. After receiving the red packet, the user's money goes directly into Wechat's change, avoiding the complicated award receiving process and giving the user WeChat Pay's original smooth experience.
Official website document address of cash red packet
You need to use a certificate to call the cash red packet API. Go to the merchant platform to download the certificate.
For an introduction to the detailed certificate on the official website, click to view
Because the cash red packet is deducted from the merchant platform balance, the merchant platform account balance must have sufficient balance.
The following is the detailed code for calling the red packet API:
1. MD5 encryption class of signature:
Summary description of / MD5UtilHelper. / public class MD5UtilHelper {public MD5UtilHelper () {/ TODO: add constructor logic / /} / to get uppercase MD5 signature result / public static string GetMD5 (string encypStr, string charset) {string retStr; MD5CryptoServiceProvider M5 = new MD5CryptoServiceProvider (); / / create md5 object byte [] inputBye Byte [] outputBye; / / converts strings to byte arrays using GB2312 encoding. Try {inputBye = Encoding.GetEncoding (charset) .GetBytes (encypStr);} catch (Exception ex) {inputBye = Encoding.GetEncoding ("GB2312") .GetBytes (encypStr);} outputBye = m5.ComputeHash (inputBye); retStr = System.BitConverter.ToString (outputBye) RetStr = retStr.Replace ("-", ") .ToUpper (); return retStr;}}
2. The class that handles the parameters:
Public class RequestHandler {public RequestHandler (HttpContext httpContext) {Parameters = new Hashtable (); this.HttpContext = httpContext? HttpContext.Current;} / key / private string Key; protected HttpContext HttpContext; / request parameters / protected Hashtable Parameters; / debug Information / private string DebugInfo / initialization function / public virtual void Init () {} / get debug information / public String GetDebugInfo () {return DebugInfo;} / get the key / public string GetKey () {return Key } / set key / public void SetKey (string key) {this.Key = key } / set parameter values / public void SetParameter (string parameter, string parameterValue) {if (parameter! = null & & parameter! = ") {if (Parameters.Contains (parameter)) {Parameters.Remove (parameter);} Parameters.Add (parameter, parameterValue) }} / create a md5 digest. The rule is: sort by parameter name Amurz. Parameters that encounter null values do not participate in the signature / parameter name / / parameter value / key and value are usually used to fill the last set of parameters / public virtual string CreateMd5Sign (string key, string value) {StringBuilder sb = new StringBuilder () ArrayList akeys = new ArrayList (Parameters.Keys); akeys.Sort (); foreach (string k in akeys) {string v = (string) Parameters [k] If (null! = v & "" .Compareto (v)! = 0 & & "sign" .Compareto (k)! = 0 & & "key" .Compareto (k)! = 0) {sb.Append (k + "=" + v + "&");}} sb.Append (key + "=" + value) String sign = MD5UtilHelper.GetMD5 (sb.ToString (), GetCharset ()). ToUpper (); return sign;} / output XML / public string ParseXML () {StringBuilder sb = new StringBuilder (); sb.Append ("); foreach (string k in Parameters.Keys) {string v = (string) Parameters [k] If (Regex.IsMatch (v, @ "^ [0-9.] $") {sb.Append ("" + v + ");} else {sb.Append (");}} sb.Append ("); return sb.ToString () } / set debug information / public void SetDebugInfo (String debugInfo) {this.DebugInfo = debugInfo;} public Hashtable GetAllParameters () {return this.Parameters;} protected virtual string GetCharset () {return this.HttpContext.Request.ContentEncoding.BodyName;}}
3. Call the cash red packet processing class:
/ Enterprise ID WeChat Pay interface / public static class TenPay {# region Enterprise sends red packets to users / it is used for enterprises to send red packets to Wechat users / currently supports sending red packets to the openid individuals of specified Wechat users / apiclient_cert.p12 certificate password is the merchant number / Wechat account Pay the physical location of the certificate that requires the xml data / apiclient_cert.p12 of post (for example: e:\ projects\ document\ Wechat Merchant platform Certificate\ Merchant platform API Certificate / public static string Sendredpack (string data) String certPassword,string certPath, int timeOut = Config.TIME_OUT) {var urlFormat = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"; String cert = certPath; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback (CheckValidationResult); X509Certificate2 cer = new X509Certificate2 (cert, certPassword, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet); var formDataBytes = data = = null? New byte [0]: Encoding.UTF8.GetBytes (data); MemoryStream ms = new MemoryStream (); ms.Write (formDataBytes, 0, formDataBytes.Length); ms.Seek (0, SeekOrigin.Begin); / / set pointer reading position HttpWebRequest request = (HttpWebRequest) WebRequest.Create (urlFormat); request.ClientCertificates.Add (cer); request.Method = "POST"; request.Timeout = timeOut; request.UserAgent = "Mozilla/5.0 (Windows NT 6.1) WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36 "; # region input binary stream if (ms! = null) {ms.Position = 0; / / Direct write stream Stream requestStream = request.GetRequestStream (); byte [] buffer = new byte [1024]; int bytesRead = 0 While ((bytesRead = ms.Read (buffer, 0, buffer.Length))! = 0) {requestStream.Write (buffer, 0, bytesRead);} ms.Close (); / / close file access} # endregion HttpWebResponse response = (HttpWebResponse) request.GetResponse () Using (Stream responseStream = response.GetResponseStream ()) {using (StreamReader myStreamReader = new StreamReader (responseStream, Encoding.GetEncoding ("utf-8")) {string retString = myStreamReader.ReadToEnd (); return retString;}} private static bool CheckValidationResult (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) {if (errors = = SslPolicyErrors.None) return true; return false;} # endregion}
4. Call the cash red packet API
# region send red packet bool fals = false; / / record whether the red packet was sent successfully string xmlResult = null; / / the xmlstring certPath returned by the cash red packet API xmlstring certPath = null; / / the certificate is in the physical location of the server string data = null; / / the data try {/ / create the payment response object RequestHandler packageReqHandler = new RequestHandler (null); / / initialize packageReqHandler.Init (); string nonceStr = TenPayV3Util.GetNoncestr () / / timestamp / / set package order parameter packageReqHandler.SetParameter ("nonce_str", nonceStr); / / Random string, no longer than 32-bit packageReqHandler.SetParameter ("mch_billno", System.Configuration.ConfigurationManager.AppSettings ["TenPayV3_MchId"] + model.JournalNumber); / / Merchant order number (each order number must be unique): a number that cannot be repeated within a day in mch_id+yyyymmdd+10 bits. The API supports reentry based on the merchant's order number, and can be called again if a timeout occurs. PackageReqHandler.SetParameter ("mch_id", System.Configuration.ConfigurationManager.AppSettings ["TenPayV3_MchId"]); / the merchant number packageReqHandler.SetParameter ("wxappid", System.Configuration.ConfigurationManager.AppSettings ["TenPayV3_AppId"]) assigned by WeChat Pay; / / the public account ID assigned by Wechat (the enterprise account corpid is the appId). All appid passed into the API should be the official account appid (applied for by mp.weixin.qq.com), not the appid of APP (applied for by open.weixin.qq.com). PackageReqHandler.SetParameter ("send_name", "test"); / / merchant name packageReqHandler.SetParameter ("re_openid", model.BankCard); / / user openid the openid packageReqHandler.SetParameter of the user receiving red packets under wxappid ("total_amount", Convert.ToInt32 ((decimal) (model.Amount * 100m)) .ToString (CultureInfo.InvariantCulture)); / / payment unit packageReqHandler.SetParameter ("total_num", "1") / / Total number of red packet distributors packageReqHandler.SetParameter ("wishing", "test red packet"); / / red packet blessing message packageReqHandler.SetParameter ("client_ip", HttpContext.Current.Request.UserHostAddress); / / Ip address packageReqHandler.SetParameter ("act_name", "test red packet"); / / activity name packageReqHandler.SetParameter ("remark", "test red packet") / Note string sign = packageReqHandler.CreateMd5Sign ("key", System.Configuration.ConfigurationManager.AppSettings ["TenPayV3_Key"]); packageReqHandler.SetParameter ("sign", sign); / / signature data = packageReqHandler.ParseXML (); certPath = Server.MapPath ("~ /") + System.Configuration.ConfigurationManager.AppSettings ["certPath"]; xmlResult = Sendredpack (data, System.Configuration.ConfigurationManager.AppSettings ["TenPayV3_MchId"], certPath); var res = XDocument.Parse (xmlResult) String return_code = res.Element ("xml"). Element ("return_code"). Value; if ("SUCCESS" .equals (return_code)) {string result_code = res.Element ("xml"). Element ("result_code"). Value; if ("SUCCESS" .equals (result_code)) {fals = true;}} catch (Exception exception) {} # endregion
Note: the folder where the certificate is located. IIS must have permission to operate on this folder.
The above is all the contents of the article "how to send red packets to users in the development of C# official account". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.