紅包功能簡單介紹:php
一、商戶調用接口時,經過指定發送對象以及發送金額的方式發放紅包,這樣的方式,容許商戶靈活的應用於各類各樣豐富的活動場景api
二、領取到紅包後,用戶的資金直接進入微信零錢,避免繁複的領獎流程,帶給用戶微信支付原生的流暢體驗數組
現金紅包官網文檔地址:https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_1服務器
調用現金紅包接口須要使用到證書,請前往商戶平臺下載證書微信
官網有關詳細證書的介紹:https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=4_3app
由於發送現金紅包是從商戶平臺餘額扣款,因此商戶平臺的帳戶餘額必須有充足的餘額ide
下面是調用紅包接口詳細代碼:一、簽名的MD5加密類:函數
1 /// <summary> 2 /// MD5UtilHelper 的摘要說明。 3 /// </summary> 4 public class MD5UtilHelper 5 { 6 public MD5UtilHelper() 7 { 8 // 9 // TODO: 在此處添加構造函數邏輯 10 // 11 } 12 13 /// <summary> 14 /// 獲取大寫的MD5簽名結果 15 /// </summary> 16 /// <param name="encypStr"></param> 17 /// <param name="charset"></param> 18 /// <returns></returns> 19 public static string GetMD5(string encypStr, string charset) 20 { 21 string retStr; 22 MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider(); 23 24 //建立md5對象 25 byte[] inputBye; 26 byte[] outputBye; 27 28 //使用GB2312編碼方式把字符串轉化爲字節數組. 29 try 30 { 31 inputBye = Encoding.GetEncoding(charset).GetBytes(encypStr); 32 } 33 catch (Exception ex) 34 { 35 inputBye = Encoding.GetEncoding("GB2312").GetBytes(encypStr); 36 } 37 outputBye = m5.ComputeHash(inputBye); 38 39 retStr = System.BitConverter.ToString(outputBye); 40 retStr = retStr.Replace("-", "").ToUpper(); 41 return retStr; 42 } 43 }
二、處理參數的類:post
1 public class RequestHandler 2 { 3 4 public RequestHandler(HttpContext httpContext) 5 { 6 Parameters = new Hashtable(); 7 8 this.HttpContext = httpContext ?? HttpContext.Current; 9 10 } 11 /// <summary> 12 /// 密鑰 13 /// </summary> 14 private string Key; 15 16 protected HttpContext HttpContext; 17 18 /// <summary> 19 /// 請求的參數 20 /// </summary> 21 protected Hashtable Parameters; 22 23 /// <summary> 24 /// debug信息 25 /// </summary> 26 private string DebugInfo; 27 28 /// <summary> 29 /// 初始化函數 30 /// </summary> 31 public virtual void Init() 32 { 33 } 34 /// <summary> 35 /// 獲取debug信息 36 /// </summary> 37 /// <returns></returns> 38 public String GetDebugInfo() 39 { 40 return DebugInfo; 41 } 42 /// <summary> 43 /// 獲取密鑰 44 /// </summary> 45 /// <returns></returns> 46 public string GetKey() 47 { 48 return Key; 49 } 50 /// <summary> 51 /// 設置密鑰 52 /// </summary> 53 /// <param name="key"></param> 54 public void SetKey(string key) 55 { 56 this.Key = key; 57 } 58 59 /// <summary> 60 /// 設置參數值 61 /// </summary> 62 /// <param name="parameter"></param> 63 /// <param name="parameterValue"></param> 64 public void SetParameter(string parameter, string parameterValue) 65 { 66 if (parameter != null && parameter != "") 67 { 68 if (Parameters.Contains(parameter)) 69 { 70 Parameters.Remove(parameter); 71 } 72 73 Parameters.Add(parameter, parameterValue); 74 } 75 } 76 77 78 /// <summary> 79 /// 建立md5摘要,規則是:按參數名稱a-z排序,遇到空值的參數不參加簽名 80 /// </summary> 81 /// <param name="key">參數名</param> 82 /// <param name="value">參數值</param> 83 /// key和value一般用於填充最後一組參數 84 /// <returns></returns> 85 public virtual string CreateMd5Sign(string key, string value) 86 { 87 StringBuilder sb = new StringBuilder(); 88 89 ArrayList akeys = new ArrayList(Parameters.Keys); 90 akeys.Sort(); 91 92 foreach (string k in akeys) 93 { 94 string v = (string)Parameters[k]; 95 if (null != v && "".CompareTo(v) != 0 96 && "sign".CompareTo(k) != 0 && "key".CompareTo(k) != 0) 97 { 98 sb.Append(k + "=" + v + "&"); 99 } 100 } 101 102 sb.Append(key + "=" + value); 103 string sign = MD5UtilHelper.GetMD5(sb.ToString(), GetCharset()).ToUpper(); 104 105 return sign; 106 } 107 108 /// <summary> 109 /// 輸出XML 110 /// </summary> 111 /// <returns></returns> 112 public string ParseXML() 113 { 114 StringBuilder sb = new StringBuilder(); 115 sb.Append("<xml>"); 116 foreach (string k in Parameters.Keys) 117 { 118 string v = (string)Parameters[k]; 119 if (Regex.IsMatch(v, @"^[0-9.]$")) 120 { 121 122 sb.Append("<" + k + ">" + v + "</" + k + ">"); 123 } 124 else 125 { 126 sb.Append("<" + k + "><![CDATA[" + v + "]]></" + k + ">"); 127 } 128 129 } 130 sb.Append("</xml>"); 131 return sb.ToString(); 132 } 133 134 135 136 /// <summary> 137 /// 設置debug信息 138 /// </summary> 139 /// <param name="debugInfo"></param> 140 public void SetDebugInfo(String debugInfo) 141 { 142 this.DebugInfo = debugInfo; 143 } 144 145 public Hashtable GetAllParameters() 146 { 147 return this.Parameters; 148 } 149 150 protected virtual string GetCharset() 151 { 152 return this.HttpContext.Request.ContentEncoding.BodyName; 153 } 154 }
三、調用現金紅包處理類:測試
1 /// <summary> 2 /// 企業號微信支付接口 3 /// </summary> 4 public static class TenPay 5 { 6 7 #region 企業向用戶發紅包 8 /// <summary> 9 /// 用於企業向微信用戶我的發紅包 10 /// 目前支持向指定微信用戶的openid我的發紅包 11 /// </summary> 12 /// <param name="certPassword">apiclient_cert.p12證書密碼即商戶號</param> 13 /// <param name="data">微信支付須要post的xml數據</param> 14 /// <param name="certPath">apiclient_cert.p12的證書物理位置(例如:E:\projects\文檔\微信商戶平臺證書\商戶平臺API證書</param> 15 /// <param name="timeOut"></param> 16 /// <returns></returns> 17 public static string Sendredpack(string data, string certPassword,string certPath, int timeOut = Config.TIME_OUT) 18 { 19 var urlFormat = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"; 20 string cert = certPath; 21 22 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); 23 X509Certificate2 cer = new X509Certificate2(cert, certPassword, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet); 24 25 var formDataBytes = data == null ? new byte[0] : Encoding.UTF8.GetBytes(data); 26 MemoryStream ms = new MemoryStream(); 27 ms.Write(formDataBytes, 0, formDataBytes.Length); 28 ms.Seek(0, SeekOrigin.Begin);//設置指針讀取位置 29 30 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlFormat); 31 request.ClientCertificates.Add(cer); 32 request.Method = "POST"; 33 request.Timeout = timeOut; 34 35 request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"; 36 37 #region 輸入二進制流 38 if (ms != null) 39 { 40 ms.Position = 0; 41 //直接寫入流 42 Stream requestStream = request.GetRequestStream(); 43 byte[] buffer = new byte[1024]; 44 int bytesRead = 0; 45 while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) != 0) 46 { 47 requestStream.Write(buffer, 0, bytesRead); 48 } 49 ms.Close();//關閉文件訪問 50 } 51 #endregion 52 53 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 54 55 using (Stream responseStream = response.GetResponseStream()) 56 { 57 using (StreamReader myStreamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"))) 58 { 59 string retString = myStreamReader.ReadToEnd(); 60 return retString; 61 } 62 } 63 } 64 private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) 65 { 66 if (errors == SslPolicyErrors.None) 67 return true; 68 return false; 69 } 70 #endregion 71 72 }
四、調用現金紅包接口
1 #region 發送紅包 2 bool fals = false; //記錄發送紅包是否成功 3 string xmlResult = null; //現金紅包接口返回的xml 4 string certPath = null; //證書在服務器的物理位置 5 string data = null; //調用現金紅包接口須要的數據 6 try 7 { 8 //建立支付應答對象 9 RequestHandler packageReqHandler = new RequestHandler(null); 10 //初始化 11 packageReqHandler.Init(); 12 string nonceStr = TenPayV3Util.GetNoncestr(); //時間戳 13 //設置package訂單參數 14 packageReqHandler.SetParameter("nonce_str", nonceStr); //隨機字符串,不長於32位 15 packageReqHandler.SetParameter("mch_billno", System.Configuration.ConfigurationManager.AppSettings["TenPayV3_MchId"] + model.JournalNumber);//商戶訂單號(每一個訂單號必須惟一)組成:mch_id+yyyymmdd+10位一天內不能重複的數字。接口根據商戶訂單號支持重入,如出現超時可再調用。 16 packageReqHandler.SetParameter("mch_id", System.Configuration.ConfigurationManager.AppSettings["TenPayV3_MchId"]); //微信支付分配的商戶號 17 packageReqHandler.SetParameter("wxappid", System.Configuration.ConfigurationManager.AppSettings["TenPayV3_AppId"]);//微信分配的公衆帳號ID(企業號corpid即爲此appId)。接口傳入的全部appid應該爲公衆號的appid(在mp.weixin.qq.com申請的),不能爲APP的appid(在open.weixin.qq.com申請的)。 18 packageReqHandler.SetParameter("send_name", "測試");//商戶名稱 19 packageReqHandler.SetParameter("re_openid", model.BankCard); //用戶openid 接受紅包的用戶用戶在wxappid下的openid 20 packageReqHandler.SetParameter("total_amount", Convert.ToInt32((decimal)(model.Amount * 100M)).ToString(CultureInfo.InvariantCulture)); //付款金額 單位分 21 packageReqHandler.SetParameter("total_num", "1"); //紅包發放總人數 22 packageReqHandler.SetParameter("wishing", "測試紅包"); //紅包祝福語 23 packageReqHandler.SetParameter("client_ip", HttpContext.Current.Request.UserHostAddress);//Ip地址 24 packageReqHandler.SetParameter("act_name", "測試紅包");//活動名稱 25 packageReqHandler.SetParameter("remark", "測試紅包"); //備註 26 string sign = packageReqHandler.CreateMd5Sign("key", System.Configuration.ConfigurationManager.AppSettings["TenPayV3_Key"]); 27 packageReqHandler.SetParameter("sign", sign); //簽名 28 data = packageReqHandler.ParseXML(); 29 certPath = Server.MapPath("~/") + System.Configuration.ConfigurationManager.AppSettings["certPath"]; 30 xmlResult = Sendredpack(data, System.Configuration.ConfigurationManager.AppSettings["TenPayV3_MchId"],certPath); 31 var res = XDocument.Parse(xmlResult); 32 string return_code = res.Element("xml").Element("return_code").Value; 33 if ("SUCCESS".Equals(return_code)) 34 { 35 string result_code = res.Element("xml").Element("result_code").Value; 36 if ("SUCCESS".Equals(result_code)) 37 { 38 fals = true; 39 } 40 } 41 } 42 catch (Exception exception) 43 { 44 } 45 #endregion
注意:證書所在文件夾權限,IIS必須有權限對該文件夾操做的權限。