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:NOTDELETEDEMOapiclient_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);