ASP.NET微信公眾號用於給指定OpenId用戶發送紅包 微信公眾號要實現對指定用戶發送紅包,必須指定一個存放兵發放金額的商戶號,在微信商戶平臺裡面申請商戶號並獲取相關參數例如發送紅包所要用到的安全證書apiclient_cert.p12。下麵分幾步驟講解: 紅包功能簡單介紹: 1、商戶調用介面時 ...
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);