1. 程式人生 > 實用技巧 >.net core 微信公眾號開發(一)

.net core 微信公眾號開發(一)

一: 登入微信公眾平臺:進行註冊

(注意:請通讀整篇文章後,再進行實操,免走彎路)

https://mp.weixin.qq.com/ ,點選立即註冊,選擇你需要的賬號型別,

這個是各種型別的區分:https://kf.qq.com/faq/170815aUZjeQ170815mU7bI7.htm,

大致總結:訂閱號沒有服務號許可權多,型別個人沒有型別企業註冊麻煩,個人無法認證,企業可認證  

註冊過程中,可分為:個人/企業等(企業,自媒體等註冊時,需要組織代號,經營許可證,對公賬戶等),這塊我選擇註冊的是個人賬號(需要上傳手持身份證的照片)

二:微信公眾號基礎操作

1:首先,瞭解一下整個工作流程(開發-->介面許可權,可看見開發者的介面許可權)

  

2:開發前的準備

開發前,必須設定好 開發-->基礎配置-->【伺服器配置】

  

如上圖所示:何進行伺服器驗證呢?

前提:

a: 一個對外的介面(微信伺服器會通過該介面,傳遞給你4個引數:加密簽名,時間戳,隨機數,隨機字串)

b:頁面填寫時,還會有個:Token

介面處理邏輯:

  wechat server ---> url :  傳入【加密簽名,時間戳,隨機數,隨機字串】--> 將【Token,時間戳,隨機數】排序並連線成一個字串

          進行sha1加密,得到的字串 與 【加密簽名】進行對比,一致則表示通過,並返回【隨機字串】

   程式碼:

 1         [Route("wechat")]
 2         [HttpGet]
 3         public ActionResult WechatValidation(string echoStr,string signature,string timestamp,string nonce)
 4         {
 5             string filename = "1.text";
 6             string webRootPath = _hostingEnvironment.WebRootPath;
 7
string contentRootPath = _hostingEnvironment.ContentRootPath; 8 string fullpath = Path.Combine(webRootPath, filename); 9 if (!System.IO.File.Exists(fullpath)) 10 { 11 System.IO.File.Create(fullpath).Close(); 12 } 13 14 System.IO.File.AppendAllText(fullpath, $"\r\nTime:{DateTime.Now},string echoStr:{echoStr},string signature:{signature},string timestamp:{timestamp},string nonce:{nonce}"); 15 16 var token = "wechat"; 17 var checkResult = CheckSignature(token, signature, timestamp, nonce); 18 return Content(echoStr); 19 } 20 21 22 private bool CheckSignature(string token, string signature, string timestamp, string nonce) 23 { 24 25 //建立陣列,將 Token, timestamp, nonce 三個引數加入陣列 26 string[] array = { token, timestamp, nonce }; 27 //進行排序 28 Array.Sort(array); 29 //拼接為一個字串 30 var tempStr = String.Join("", array); 31 //對字串進行 SHA1加密 32 tempStr = Get_SHA1_Method2(tempStr); 33 //判斷signature 是否正確 34 if (tempStr.Equals(signature)) 35 { 36 return true; 37 } 38 else 39 { 40 return false; 41 } 42 } 43 44 public string Get_SHA1_Method2(string strSource) 45 { 46 string strResult = ""; 47 48 //Create 49 System.Security.Cryptography.SHA1 md5 = System.Security.Cryptography.SHA1.Create(); 50 51 //注意編碼UTF8、UTF7、Unicode等的選擇 52 byte[] bytResult = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strSource)); 53 54 //位元組型別的陣列轉換為字串 55 for (int i = 0; i < bytResult.Length; i++) 56 { 57 //16進位制轉換 58 strResult = strResult + bytResult[i].ToString("X"); 59 } 60 return strResult.ToLower(); 61 }
View Code

c:介面寫完,即可部署伺服器