ASP.NET微信公众号用于给指定OpenId用户发送红包
微信公众号要实现对指定用户发送红包,必须指定一个存放兵发放金额的商户号,在微信商户平台里面申请商户号并获取相关参数例如发送红包所要用到的安全证书apiclient_cert.p12。下面分几步骤讲解:
红包功能简单介绍:
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
因为发送现金红包是从商户平台余额扣款,所以商户平台的账户余额必须有充足的余额
一、获取关注微信公众号用户OpenId
在微信商户平台获取以下参数:MchId【微信支付商户号】、AppId【应用ID】、AppSecret【应用密钥】、AppKey【API密钥】
private void GetUserOpenId()
{ string code = Request.QueryString["code"];string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", PayConfig.AppId, PayConfig.AppSecret, code);
string returnStr = HttpUtil.Send("", url);
var obj = JsonConvert.DeserializeObject<OpenModel>(returnStr);
url = string.Format("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type=refresh_token&refresh_token={1}", PayConfig.AppId, obj.refresh_token);
returnStr = HttpUtil.Send("", url); obj = JsonConvert.DeserializeObject<OpenModel>(returnStr);url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}", obj.access_token, obj.openid);
returnStr = HttpUtil.Send("", url); acc = obj.access_token; Session["acc"] = acc; OpenId = obj.openid;}
二、构造发送红包金额数及实体类参数
/// <summary>
/// 构造参数 /// </summary> /// <returns></returns> public string GetJsApiParameters() { #region 红包金额随机数Random rd1 = new Random();
int a = rd1.Next(30,100);//生成0.3-1元之间的随机数(金额单位/分) if (a > 0) { //float f = (float)(a * 0.01); //Num = f.ToString(); Num = a.ToString(); } else if (a <30||a>100) { Num = "30";//若红包金额出现异常,设置固定金额为0.3元 }#endregion 红包金额随机数
int iMin = 1000;
int iMax = 9999; Random rd = new Random();//构造随机数 string strMch_billno = PayConfig.MchId + DateTime.Now.ToString("yyyyMMddHHmmss") + rd.Next(iMin, iMax).ToString();//商户订单号 //随机字符串 NonceStr = TenpayUtil.getNoncestr();//创建支付应答对象
var packageReqHandler = new RequestHandler(Context); //初始化 packageReqHandler.init(); packageReqHandler.setParameter("act_name", "活动名称:红包抽奖"); packageReqHandler.setParameter("client_ip", PayConfig.IP);//调用的域名IP packageReqHandler.setParameter("mch_billno", strMch_billno);//商户订单号 packageReqHandler.setParameter("mch_id", PayConfig.MchId);//商户号 packageReqHandler.setParameter("nonce_str", NonceStr);//随机数 packageReqHandler.setParameter("remark", "备注信息");//这里需要填写缴费用户的信息(编号、名称) packageReqHandler.setParameter("re_openid", OpenId);//发送的指定的OpenId packageReqHandler.setParameter("send_name", "发送方名称");//发送方 packageReqHandler.setParameter("total_amount", Num);//发送金额 packageReqHandler.setParameter("total_num", "1");//发送红包个数 packageReqHandler.setParameter("wishing", "感谢您参加红包抽奖活动,祝您生活愉快!");//备注 packageReqHandler.setParameter("wxappid", PayConfig.AppId);//appId应用ID //packageReqHandler.setParameter("scene_id", PRODUCT_2); packageReqHandler.setParameter("sign", packageReqHandler.CreateMd5Sign("key", PayConfig.AppKey));//生成签名string parameters = packageReqHandler.parseXML();//构造XML
return parameters; LogUtil.WriteLog("返回构造参数XML========" + parameters); }三、定义红包接口URL
string strUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";//发送红包的API接口
四、定义微信认证证书接口及要解决的返回Json数据
/// <summary>
/// 微信需要证书接口 /// </summary> /// <param name="url"></param> /// <param name="postdata"></param> /// <returns></returns> public string Postxmltourl(string url, string postData) { Stream outstream = null; Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; Encoding encoding = Encoding.UTF8; byte[] data = encoding.GetBytes(postData); // 准备请求... try { //CerPath证书路径,这里是本机的路径,实际应用中,按照实际情况来填写 string certPath = @"D:\NOTDELETE\DEMO\apiclient_cert.p12"; //证书密码 string password = "证书密码为微信商户支付号"; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);// X509Certificate2 cert = new X509Certificate2(certPath, password, X509KeyStorageFlags.MachineKeySet);
X509Certificate2 cert = new X509Certificate2(certPath, password); // 设置参数 request = WebRequest.Create(url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer;//不可少(个人理解为,返回的时候需要验证) request.AllowAutoRedirect = true; request.Method = "POST"; request.ContentType = "text/xml"; request.ContentLength = data.Length; request.ClientCertificates.Add(cert);//添加证书请求 outstream = request.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Close(); //发送请求并获取相应回应数据 response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 instream = response.GetResponseStream(); sr = new StreamReader(instream, encoding); //返回结果网页(html)代码 string content = sr.ReadToEnd(); string err = string.Empty; return content;}
catch (Exception ex)//获取异常错误信息 { string err = ex.Message; return string.Empty; }五、定义结果接受证书请求
string strResult = Postxmltourl(strUrl, strData);