调用微信公众号现金红包接口给用户发送红包
红包功能简单介绍:
1、商户调用接口时,通过指定发送对象以及发送金额的方式发放红包,这样的方式,允许商户灵活的应用于各种各样丰富的活动场景
2、领取到红包后,用户的资金直接进入微信零钱,避免繁复的领奖流程,带给用户微信支付原生的流畅体验
现金红包官网文档地址: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_3
因为发送现金红包是从商户平台余额扣款,所以商户平台的账户余额必须有充足的余额
下面是调用红包接口详细代码:1、签名的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 }
2、处理参数的类:
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 }
3、调用现金红包处理类:
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 }
4、调用现金红包接口
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必须有权限对该文件夹操作的权限。