紅包功能簡單介紹:
1、商戶調用接口時,通過指定發送對象以及發送金額的方式發放紅包,這樣的方式,允許商戶靈活的應用于各種各樣豐富的活動場景
2、領取到紅包后,用戶的資金直接進入微信零錢,避免繁復的領獎流程,帶給用戶微信支付原生的流暢體驗
現金紅包官網文檔地址
調用現金紅包接口需要使用到證書,請前往商戶平臺下載證書
官網有關詳細證書的介紹,點擊查看
因為發送現金紅包是從商戶平臺余額扣款,所以商戶平臺的賬戶余額必須有充足的余額
下面是調用紅包接口詳細代碼:
1、簽名的MD5加密類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
/// <summary> /// MD5UtilHelper 的摘要說明。 /// </summary> public class MD5UtilHelper { public MD5UtilHelper() { // // TODO: 在此處添加構造函數邏輯 // } /// <summary> /// 獲取大寫的MD5簽名結果 /// </summary> /// <param name="encypStr"></param> /// <param name="charset"></param> /// <returns></returns> public static string GetMD5( string encypStr, string charset) { string retStr; MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider(); //創建md5對象 byte [] inputBye; byte [] outputBye; //使用GB2312編碼方式把字符串轉化為字節數組. 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、處理參數的類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
|
public class RequestHandler { public RequestHandler(HttpContext httpContext) { Parameters = new Hashtable(); this .HttpContext = httpContext ?? HttpContext.Current; } /// <summary> /// 密鑰 /// </summary> private string Key; protected HttpContext HttpContext; /// <summary> /// 請求的參數 /// </summary> protected Hashtable Parameters; /// <summary> /// debug信息 /// </summary> private string DebugInfo; /// <summary> /// 初始化函數 /// </summary> public virtual void Init() { } /// <summary> /// 獲取debug信息 /// </summary> /// <returns></returns> public String GetDebugInfo() { return DebugInfo; } /// <summary> /// 獲取密鑰 /// </summary> /// <returns></returns> public string GetKey() { return Key; } /// <summary> /// 設置密鑰 /// </summary> /// <param name="key"></param> public void SetKey( string key) { this .Key = key; } /// <summary> /// 設置參數值 /// </summary> /// <param name="parameter"></param> /// <param name="parameterValue"></param> public void SetParameter( string parameter, string parameterValue) { if (parameter != null && parameter != "" ) { if (Parameters.Contains(parameter)) { Parameters.Remove(parameter); } Parameters.Add(parameter, parameterValue); } } /// <summary> /// 創建md5摘要,規則是:按參數名稱a-z排序,遇到空值的參數不參加簽名 /// </summary> /// <param name="key">參數名</param> /// <param name="value">參數值</param> /// key和value通常用于填充最后一組參數 /// <returns></returns> 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; } /// <summary> /// 輸出XML /// </summary> /// <returns></returns> public string ParseXML() { StringBuilder sb = new StringBuilder(); sb.Append( "<xml>" ); foreach ( string k in Parameters.Keys) { string v = ( string )Parameters[k]; if (Regex.IsMatch(v, @"^[0-9.]$" )) { sb.Append( "<" + k + ">" + v + "</" + k + ">" ); } else { sb.Append( "<" + k + "><![CDATA[" + v + "]]></" + k + ">" ); } } sb.Append( "</xml>" ); return sb.ToString(); } /// <summary> /// 設置debug信息 /// </summary> /// <param name="debugInfo"></param> 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、調用現金紅包處理類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
/// <summary> /// 企業號微信支付接口 /// </summary> public static class TenPay { #region 企業向用戶發紅包 /// <summary> /// 用于企業向微信用戶個人發紅包 /// 目前支持向指定微信用戶的openid個人發紅包 /// </summary> /// <param name="certPassword">apiclient_cert.p12證書密碼即商戶號</param> /// <param name="data">微信支付需要post的xml數據</param> /// <param name="certPath">apiclient_cert.p12的證書物理位置(例如:E:\projects\文檔\微信商戶平臺證書\商戶平臺API證書</param> /// <param name="timeOut"></param> /// <returns></returns> 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); //設置指針讀取位置 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 輸入二進制流 if (ms != null ) { ms.Position = 0; //直接寫入流 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(); //關閉文件訪問 } #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、調用現金紅包接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
#region 發送紅包 bool fals = false ; //記錄發送紅包是否成功 string xmlResult = null ; //現金紅包接口返回的xml string certPath = null ; //證書在服務器的物理位置 string data = null ; //調用現金紅包接口需要的數據 try { //創建支付應答對象 RequestHandler packageReqHandler = new RequestHandler( null ); //初始化 packageReqHandler.Init(); string nonceStr = TenPayV3Util.GetNoncestr(); //時間戳 //設置package訂單參數 packageReqHandler.SetParameter( "nonce_str" , nonceStr); //隨機字符串,不長于32位 packageReqHandler.SetParameter( "mch_billno" , System.Configuration.ConfigurationManager.AppSettings[ "TenPayV3_MchId" ] + model.JournalNumber); //商戶訂單號(每個訂單號必須唯一)組成:mch_id+yyyymmdd+10位一天內不能重復的數字。接口根據商戶訂單號支持重入,如出現超時可再調用。 packageReqHandler.SetParameter( "mch_id" , System.Configuration.ConfigurationManager.AppSettings[ "TenPayV3_MchId" ]); //微信支付分配的商戶號 packageReqHandler.SetParameter( "wxappid" , System.Configuration.ConfigurationManager.AppSettings[ "TenPayV3_AppId" ]); //微信分配的公眾賬號ID(企業號corpid即為此appId)。接口傳入的所有appid應該為公眾號的appid(在mp.weixin.qq.com申請的),不能為APP的appid(在open.weixin.qq.com申請的)。 packageReqHandler.SetParameter( "send_name" , "測試" ); //商戶名稱 packageReqHandler.SetParameter( "re_openid" , model.BankCard); //用戶openid 接受紅包的用戶用戶在wxappid下的openid packageReqHandler.SetParameter( "total_amount" , Convert.ToInt32(( decimal )(model.Amount * 100M)).ToString(CultureInfo.InvariantCulture)); //付款金額 單位分 packageReqHandler.SetParameter( "total_num" , "1" ); //紅包發放總人數 packageReqHandler.SetParameter( "wishing" , "測試紅包" ); //紅包祝福語 packageReqHandler.SetParameter( "client_ip" , HttpContext.Current.Request.UserHostAddress); //Ip地址 packageReqHandler.SetParameter( "act_name" , "測試紅包" ); //活動名稱 packageReqHandler.SetParameter( "remark" , "測試紅包" ); //備注 string sign = packageReqHandler.CreateMd5Sign( "key" , System.Configuration.ConfigurationManager.AppSettings[ "TenPayV3_Key" ]); packageReqHandler.SetParameter( "sign" , sign); //簽名 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 |
注意:證書所在文件夾權限,IIS必須有權限對該文件夾操作的權限。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/lx_nhs/article/details/81302387