最近 公司要求作一個微信公衆號的功能,發現後臺功能沒法實現,因此須要公衆號開發,而後本身再網上 看了一些代碼,發現.net這塊兒不少不完善,而後本身就寫了一個完整的。服務器
目錄微信
1,建立mvc項目mvc
2,n g r o k內網穿透post
3,微信測試號測試
4,vs調試編碼
建立mvc項目加密
建立項目,取名WeChatTesturl
選擇MVCspa
添加控制器 WeChat,項目結構如圖(控制器寫錯了,應該爲WeChat).net
n g r o k內網穿透
直接進入官網下載便可,下載地址:https://ngrok.com/download,我本身下載的
如今的壓縮包,直接解壓,而後打開ngrok.exe文件,輸入ngrok http 80,按回車鍵,能夠看到以下界面,訪問 http://275c2c0032c8.ngrok.io 就是對應本地的 http://localhost:80
將WeChatTest發佈到iis,在這裏咱們直接發佈源代碼,主要是爲了後面的調試
訪問http://275c2c0032c8.ngrok.io,以下圖。
若是看到該界面,則能夠經過外網直接訪問了。能夠關掉手機wifi,直接使用手機訪問該網址
接口配置信息
當咱們點提交的時候,騰訊的公衆號服務器,向咱們本身搭建的服務器發送Get請求,url爲請求的地址,Token爲咱們在服務器後臺隨意填寫的,只要對應,就能夠
具體代碼以下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace WeChatTest.Controllers
{
public class WeChatController : Controller
{
public static string Token = "hmehomeToken";
public void index()
{
if (Request.HttpMethod.ToLower() == "get")
{
Valid();
}
if (Request.HttpMethod.ToLower() == "post")
{
}
}
/// <summary>
/// 檢驗signature
/// </summary>
private void Valid()
{
//微信服務器配置提交時,echoStr纔不爲空。
string echoStr = Request.QueryString["echoStr"];
if (echoStr != null)
{
if (CheckSignature())
{
if (!string.IsNullOrEmpty(echoStr))
{
Response.Write(echoStr);
Response.End();
}
}
}
}
/// <summary>
/// 驗證微信簽名
/// </summary>
/// * 將token、timestamp、nonce三個參數進行字典序排序
/// * 將三個參數字符串拼接成一個字符串進行sha1加密
/// * 開發者得到加密後的字符串可與signature對比,標識該請求來源於微信。
/// <returns></returns>
private bool CheckSignature()
{
string signature = Request.QueryString["signature"].ToString();
string timestamp = Request.QueryString["timestamp"].ToString();
string nonce = Request.QueryString["nonce"].ToString();
try
{
string[] ArrTmp = { Token, timestamp, nonce };
Array.Sort(ArrTmp); //字典排序
string tmpStr = string.Join("", ArrTmp);
SHA1 sha = SHA1.Create();
//注意編碼UTF八、UTF七、Unicode等的選擇
byte[] bytResult = sha.ComputeHash(Encoding.UTF8.GetBytes(tmpStr));
tmpStr = BitConverter.ToString(bytResult).Replace("-", "");
tmpStr = tmpStr.ToLower();
if (tmpStr == signature)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
}
return false;
}
}
}
在Vs中調試改代碼,而後訪問iis地址,若是沒有報錯,測試號管理--接口配置信息 設置以下
vs調試
這裏設置爲本地iis,要用管理員的身 打開vs,而後打開項目
在代碼中打上斷點
而後修改 爲這樣,點擊提交
斷點觸發
微信的 消息回覆,帶參二維碼,等,均可以經過這樣的方式調試
請尊重原創,轉載需帶上地址