Home > Article > WeChat Applet > WeChat public account development: Examples of how merchants send red envelopes to users
A brief introduction to the red envelope function:
1. When a merchant calls the interface, it issues red envelopes by specifying the sending object and the sending amount. This method allows merchants to flexibly apply it to various applications. Rich activity scenes
2. After receiving the red envelope, the user's funds will be directly transferred to WeChat change, avoiding the complicated award-receiving process and giving users the smooth experience of WeChat payment.
Cash Red Envelope Official Website Document address: https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_1
You need to use a certificate to call the cash red envelope interface, please go to the merchant platform to download it Certificate
Official website for detailed certificate introduction: https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=4_3
Because sending cash The red envelope is deducted from the balance of the merchant platform, so the account balance of the merchant platform must have sufficient balance
The following is the detailed code for calling the red envelope interface: 1. Signed MD5 encryption class:
/// <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 , Parameter processing class:
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. Call cash red envelope processing class:
/// <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. Call cash red envelope interface
#region 发送红包bool fals = false; //记录发送红包是否成功string xmlResult = null; //现金红包接口返回的xmlstring 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
Note: Permissions of the folder where the certificate is located, IIS You must have permission to operate on this folder.
Related articles:
PHP WeChat public account automatically sends red envelope API, php public red envelope api
Related videos:
The above is the detailed content of WeChat public account development: Examples of how merchants send red envelopes to users. For more information, please follow other related articles on the PHP Chinese website!