紅包功能簡(jiǎn)單介紹:
1、商戶(hù)調(diào)用接口時(shí),通過(guò)指定發(fā)送對(duì)象以及發(fā)送金額的方式發(fā)放紅包,這樣的方式,允許商戶(hù)靈活的應(yīng)用于各種各樣豐富的活動(dòng)場(chǎng)景
2、領(lǐng)取到紅包后,用戶(hù)的資金直接進(jìn)入微信零錢(qián),避免繁復(fù)的領(lǐng)獎(jiǎng)流程,帶給用戶(hù)微信支付原生的流暢體驗(yàn)
現(xiàn)金紅包官網(wǎng)文檔地址
調(diào)用現(xiàn)金紅包接口需要使用到證書(shū),請(qǐng)前往商戶(hù)平臺(tái)下載證書(shū)
官網(wǎng)有關(guān)詳細(xì)證書(shū)的介紹,點(diǎn)擊查看
因?yàn)榘l(fā)送現(xiàn)金紅包是從商戶(hù)平臺(tái)余額扣款,所以商戶(hù)平臺(tái)的賬戶(hù)余額必須有充足的余額
下面是調(diào)用紅包接口詳細(xì)代碼:
1、簽名的MD5加密類(lèi):
/// <summary>/// MD5UtilHelper 的摘要說(shuō)明。/// </summary>public class MD5UtilHelper{ public MD5UtilHelper() { // // TODO: 在此處添加構(gòu)造函數(shù)邏輯 // } /// <summary> /// 獲取大寫(xiě)的MD5簽名結(jié)果 /// </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(); //創(chuàng)建md5對(duì)象 byte[] inputBye; byte[] outputBye; //使用GB2312編碼方式把字符串轉(zhuǎn)化為字節(jié)數(shù)組. 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、處理參數(shù)的類(lèi):
public class RequestHandler { public RequestHandler(HttpContext httpContext) { Parameters = new Hashtable(); this.HttpContext = httpContext ?? HttpContext.Current; } /// <summary> /// 密鑰 /// </summary> private string Key; protected HttpContext HttpContext; /// <summary> /// 請(qǐng)求的參數(shù) /// </summary> protected Hashtable Parameters; /// <summary> /// debug信息 /// </summary> private string DebugInfo; /// <summary> /// 初始化函數(shù) /// </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> /// 設(shè)置密鑰 /// </summary> /// <param name="key"></param> public void SetKey(string key) { this.Key = key; } /// <summary> /// 設(shè)置參數(shù)值 /// </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> /// 創(chuàng)建md5摘要,規(guī)則是:按參數(shù)名稱(chēng)a-z排序,遇到空值的參數(shù)不參加簽名 /// </summary> /// <param name="key">參數(shù)名</param> /// <param name="value">參數(shù)值</param> /// key和value通常用于填充最后一組參數(shù) /// <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> /// 設(shè)置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、調(diào)用現(xiàn)金紅包處理類(lèi):
/// <summary> /// 企業(yè)號(hào)微信支付接口 /// </summary> public static class TenPay { #region 企業(yè)向用戶(hù)發(fā)紅包 /// <summary> /// 用于企業(yè)向微信用戶(hù)個(gè)人發(fā)紅包 /// 目前支持向指定微信用戶(hù)的openid個(gè)人發(fā)紅包 /// </summary> /// <param name="certPassword">apiclient_cert.p12證書(shū)密碼即商戶(hù)號(hào)</param> /// <param name="data">微信支付需要post的xml數(shù)據(jù)</param> /// <param name="certPath">apiclient_cert.p12的證書(shū)物理位置(例如:E:/projects/文檔/微信商戶(hù)平臺(tái)證書(shū)/商戶(hù)平臺(tái)API證書(shū)</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);//設(shè)置指針讀取位置 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 輸入二進(jìn)制流 if (ms != null) { ms.Position = 0; //直接寫(xiě)入流 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();//關(guān)閉文件訪(fǎng)問(wèn) } #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、調(diào)用現(xiàn)金紅包接口
#region 發(fā)送紅包bool fals = false; //記錄發(fā)送紅包是否成功string xmlResult = null; //現(xiàn)金紅包接口返回的xmlstring certPath = null; //證書(shū)在服務(wù)器的物理位置string data = null; //調(diào)用現(xiàn)金紅包接口需要的數(shù)據(jù)try{ //創(chuàng)建支付應(yīng)答對(duì)象 RequestHandler packageReqHandler = new RequestHandler(null); //初始化 packageReqHandler.Init(); string nonceStr = TenPayV3Util.GetNoncestr(); //時(shí)間戳 //設(shè)置package訂單參數(shù) packageReqHandler.SetParameter("nonce_str", nonceStr); //隨機(jī)字符串,不長(zhǎng)于32位 packageReqHandler.SetParameter("mch_billno", System.Configuration.ConfigurationManager.AppSettings["TenPayV3_MchId"] + model.JournalNumber);//商戶(hù)訂單號(hào)(每個(gè)訂單號(hào)必須唯一)組成:mch_id+yyyymmdd+10位一天內(nèi)不能重復(fù)的數(shù)字。接口根據(jù)商戶(hù)訂單號(hào)支持重入,如出現(xiàn)超時(shí)可再調(diào)用。 packageReqHandler.SetParameter("mch_id", System.Configuration.ConfigurationManager.AppSettings["TenPayV3_MchId"]); //微信支付分配的商戶(hù)號(hào) packageReqHandler.SetParameter("wxappid", System.Configuration.ConfigurationManager.AppSettings["TenPayV3_AppId"]);//微信分配的公眾賬號(hào)ID(企業(yè)號(hào)corpid即為此appId)。接口傳入的所有appid應(yīng)該為公眾號(hào)的appid(在mp.weixin.qq.com申請(qǐng)的),不能為APP的appid(在open.weixin.qq.com申請(qǐng)的)。 packageReqHandler.SetParameter("send_name", "測(cè)試");//商戶(hù)名稱(chēng) packageReqHandler.SetParameter("re_openid", model.BankCard); //用戶(hù)openid 接受紅包的用戶(hù)用戶(hù)在wxappid下的openid packageReqHandler.SetParameter("total_amount", Convert.ToInt32((decimal)(model.Amount * 100M)).ToString(CultureInfo.InvariantCulture)); //付款金額 單位分 packageReqHandler.SetParameter("total_num", "1"); //紅包發(fā)放總?cè)藬?shù) packageReqHandler.SetParameter("wishing", "測(cè)試紅包"); //紅包祝福語(yǔ) packageReqHandler.SetParameter("client_ip", HttpContext.Current.Request.UserHostAddress);//Ip地址 packageReqHandler.SetParameter("act_name", "測(cè)試紅包");//活動(dòng)名稱(chēng) packageReqHandler.SetParameter("remark", "測(cè)試紅包"); //備注 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
注意:證書(shū)所在文件夾權(quán)限,IIS必須有權(quán)限對(duì)該文件夾操作的權(quán)限。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注