如何使用.net構建微信服務號發(fā)送紅包-創(chuàng)新互聯(lián)

這期內容當中小編將會給大家?guī)碛嘘P如何使用.net構建微信服務號發(fā)送紅包,文章內容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

創(chuàng)新互聯(lián)建站專業(yè)為企業(yè)提供武定網站建設、武定做網站、武定網站設計、武定網站制作等企業(yè)網站建設、網頁設計與制作、武定企業(yè)網站模板建站服務,10多年武定做網站經驗,不只是建網站,更提供有價值的思路和整體網絡服務。

注:需要開通微信支付的服務號!

//跳轉微信登錄頁面
public ActionResult Index()
{
 ViewBag.url = "https://open.weixin.qq.com/connect/oauth3/authorize?appid=" + {服務號appid} + "&redirect_uri=http%3A%2F%2F" + {微信重定向域名(填寫程序域名,例如:www.xxxx.com)} + "%2F"+{程序控制器名,例如:Home}+"%2F"+{程序Action名,例如:RedirectWeChat}+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
 return View();
}

//獲取accesstoken(訪問微信接口需要)
public static string accesstoken(string WeChatWxAppId, string WeChatWxAppSecret)
{
 string strJson = HttpRequestUtil.RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", WeChatWxAppId, WeChatWxAppSecret));
 if (strJson.IndexOf("errcode") == -1)
 {
  return GetJsonValue(strJson, "access_token");
 }
 else
 {
  return "";
 }
}
//解析json
public static string GetJsonValue(string jsonStr, string key)
{
 string result = string.Empty;
 if (!string.IsNullOrEmpty(jsonStr))
 {
  key = "\"" + key.Trim('"') + "\"";
  int index = jsonStr.IndexOf(key) + key.Length + 1;
  if (index > key.Length + 1)
  {
   //先截逗號,若是最后一個,截“}”號,取最小值
   int end = jsonStr.IndexOf(',', index);
   if (end == -1)
   {
    end = jsonStr.IndexOf('}', index);
   }
   result = jsonStr.Substring(index, end - index);
   result = result.Trim(new char[] { '"', ' ', '\'' }); //過濾引號或空格
  }
 }
 return result;
}

//請求url
public static string RequestUrl(string url, string method="post")
{
 // 設置參數
 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
 CookieContainer cookieContainer = new CookieContainer();
 request.CookieContainer = cookieContainer;
 request.AllowAutoRedirect = true;
 request.Method = method;
 request.ContentType = "text/html";
 request.Headers.Add("charset", "utf-8");
 //發(fā)送請求并獲取相應回應數據
 HttpWebResponse response = request.GetResponse() as HttpWebResponse;
 //直到request.GetResponse()程序才開始向目標網頁發(fā)送Post請求
 Stream responseStream = response.GetResponseStream();
 StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
 //返回結果網頁(html)代碼
 string content = sr.ReadToEnd();
 return content;
}
//接收微信返回code
//接收微信數據獲取用戶信息
public ActionResult RedirectWeChat(string code, string state)
{
 if (string.IsNullOrEmpty(code))
 {
  return Content("您拒絕了授權!");
 }
 string access_token = accesstoken(微信AppId, 微信AppSecret);
 string st = "/tupian/20230522/access_token
 string data = RequestUrl(st);
//拿到用戶openid
string openid=GetJsonValue(data, "openid");
//獲取用戶其他信息
 string url = "/tupian/20230522/info
 data = RequestUrl(url);
string subscribe=GetJsonValue(data, "subscribe");
 if (subscribe == "0")
 {
  ///未關注
  return RedirectToAction("");
 }

 return RedirectToAction("");
}

//發(fā)送紅包Action
public ActionResult HB()
{
 string openid = "";//用戶openid
 string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"; 
 string orderNo = 商戶號 + DateTime.Now.ToString("yyyymmdd")+"隨機10位數字";//商戶訂單號 組成:mch_id+yyyymmdd+10位一天內不能重復的數字。 
 string Code = ""//32為隨機字符串; string key="key=" + "";//支付密鑰(在商戶平臺設置32為字符串) 
 Dictionary<string, string> data = new Dictionary<string, string>(); data.Add("act_name", "");//活動名稱 
 data.Add("client_ip", "192.168.1.1");//Ip地址 
 data.Add("mch_billno", orderNo);//商戶訂單號 組成:mch_id+yyyymmdd+10位一天內不能重復的數字。 
 data.Add("mch_id", "");//商戶號 
 data.Add("nonce_str", Code);//隨機字符串 
 data.Add("re_openid", openid);//用戶openid 
 data.Add("remark", "");//備注 
 data.Add("send_name","");//商戶名稱 
 data.Add("total_amount", "100");//付款金額 單位分 
 data.Add("total_num", "1");//紅包發(fā)放總人數 
 data.Add("wishing", "恭喜發(fā)財");//紅包祝福語 
 data.Add("wxappid", );//公眾賬號appid 
 string xml = GetXML(data, key);//簽名+拼接xml 
 string str=PostWebRequests(url, xml);//微信返回xml err_code=SUCCESS 就是成功
 return View(""); 
}

//發(fā)送紅包(MD5簽名+拼接XML)
public static string GetXML(Dictionary<string, string> data,string paykey)
{
 string retStr;
 MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();

 var data1=from d in data orderby d.Key select d;
 string data2 = "";
 string XML = "<xml>";
 foreach (var item in data1)
 {
  //空值不參與簽名
  if (item.Value + "" != "")
  {
   data2 += item.Key +"="+ item.Value + "&";
  }
  XML += "<" + item.Key + ">" + item.Value+""+ "</" + item.Key + ">";
 }

 data2 += paykey;
 //創(chuàng)建md5對象
 byte[] inputBye;
 byte[] outputBye;

 //使用GB2312編碼方式把字符串轉化為字節(jié)數組.
 try
 {
  inputBye = Encoding.UTF8.GetBytes(data2);
 }
 catch
 {
  inputBye = Encoding.GetEncoding("GB2312").GetBytes(data2);
 }
 outputBye = m5.ComputeHash(inputBye);

 retStr = System.BitConverter.ToString(outputBye);
 retStr = retStr.Replace("-", "").ToUpper();
 XML += "<sign>" + retStr + "</sign>";//簽名
 XML += "</xml>";
 return XML;
}

//發(fā)送紅包請求Post方法
public static string PostWebRequests(string postUrl, string menuInfo)
{
 string returnValue = string.Empty;
 try
 {
  Encoding encoding = Encoding.UTF8;
  byte[] bytes = encoding.GetBytes(menuInfo);
  string cert = @"E:\cdcert\apiclient_cert.p12";//支付證書路徑
  string password = "1212121";//支付證書密碼

  ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  X509Certificate cer = new X509Certificate(cert, password, X509KeyStorageFlags.MachineKeySet);
  HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(postUrl);
  webrequest.ClientCertificates.Add(cer);
  webrequest.Method = "post";
  webrequest.ContentLength = bytes.Length;
  webrequest.GetRequestStream().Write(bytes, 0, bytes.Length);
  HttpWebResponse webreponse = (HttpWebResponse)webrequest.GetResponse();
  Stream stream = webreponse.GetResponseStream();
  string resp = string.Empty;
  using (StreamReader reader = new StreamReader(stream))
  {
    return reader.ReadToEnd();
  }

 }
 catch (Exception ex)
 {
  return "";
 }
}

上述就是小編為大家分享的如何使用.net構建微信服務號發(fā)送紅包了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

分享名稱:如何使用.net構建微信服務號發(fā)送紅包-創(chuàng)新互聯(lián)
瀏覽地址:http://muchs.cn/article44/dshcee.html

成都網站建設公司_創(chuàng)新互聯(lián),為您提供App設計、企業(yè)網站制作、網站制作、手機網站建設用戶體驗、微信公眾號

廣告

聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

外貿網站建設