使用SQLite進行保存數據保存、Quartz進行定時獲取token、Code、QRCoder生成二維碼
相關源碼在未尾有下載連接
sqlite使用的文件需要自己創建
相關微信后台驗證需要在Config.cs 文件中配置。同時該文件使用表達式寫法
例: public static string ServerToken{return ConfigurationManager.AppSettings["ServerToken"];} == public static string ServerToken => ConfigurationManager.AppSettings["ServerToken"];
以下是webApi使用例示如下:
/*
*當沒有必生http請求時使用System.Web.HttpContext.Current.Server.MapPath()
* 會出現未將對象引用設置到對象的實例的錯誤的解決方法:
*使用System.AppDomain.CurrentDomain.BaseDirectory
*/
private static SqLiteHelper openDb = new SqLiteHelper(@"data source=" + System.Web.HttpContext.Current.Server.MapPath(@"/DBSqlite/wxdb.db") + "");
private static bool DefineExecution = true;//定義執行
private static bool isAuthCode = true;
///
/// 獲取驗票據
/// AuthReceive 是公眾號后台配置的方法
///
///
///
///
[System.Web.Http.Route("AuthReceive")]
[HttpPost]
public HttpResponseMessage AuthReceive()
{
try
{
PostModel postModel = new PostModel();
var request = HttpContext.Current.Request;
postModel.Timestamp = request.QueryString["timestamp"].ToString();
postModel.Msg_Signature = request.QueryString["msg_signature"].ToString();
postModel.Nonce = request.QueryString["Nonce"].ToString();
//HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//獲取傳統context
//HttpRequestBase request = context.Request;//定義傳統request對象
var msg = InterfaceApi.Component_verify_ticket(postModel, request.InputStream);
if (msg.InfoType == ThirdPartyInfo.component_verify_ticket.ToString())
{
Logger.Debug("msg.ComponentVerifyTicket:" + msg.ComponentVerifyTicket);
var sql =
$@"INSERT INTO WxComponentVerifyTicket (AppId,AuthorizerAppid,ComponentVerifyTicket,CreateTime,InfoType) VALUES ('{msg.AppId}','{msg.AuthorizerAppid}','{msg.ComponentVerifyTicket}',{msg.CreateTime},'{msg.InfoType}');";
var retData = openDb.ExecuteNonQuery(sql);
if (retData >= 1)
{
if (DefineExecution)//等於空立刻執行獲取Token
{
Logger.Debug("執行獲取token方法" + msg.ComponentVerifyTicket);
DefineExecution = false;
ChangeTokensJob.token();
}
}
}
else if (msg.InfoType == ThirdPartyInfo.unauthorized.ToString())
{
//取消事件 todo
}
return new HttpResponseMessage()
{
Content = new StringContent("success", Encoding.GetEncoding("UTF-8"),
"application/x-www-form-urlencoded")
};
}
catch (Exception ex)
{
Logger.Debug(@"獲取ComponentVerifyTicket出錯:" + ex);
//return Content("success");
return new HttpResponseMessage()
{
Content = new StringContent("success", Encoding.GetEncoding("UTF-8"),
"application/x-www-form-urlencoded")
};
}
}
///
/// 使授權碼獲取授權后的信息
///
///
///
[System.Web.Http.Route("ObtainAuthorizationInformation")]
[HttpPost]
public HttpResponseMessage ObtainAuthorizationInformation([FromBody]Dictionary
req)
{
var re = new ApiResponseObject()
{
ErrorCode = (int)ErrorCodeEnum.Normal,
ErrorMsg = "系統出錯了",
success = true
};
try
{
if (!string.IsNullOrWhiteSpace(req["authCode"]))
{
var sqlToken = string.Format(@"select * from WxComponentAccessToken Order by ID Desc limit 0,1");
var model = openDb.ExecuteModel
(sqlToken);
var data= InterfaceApi.Query_auth(model.ComponentAccessToken, req["authCode"]);
re.Data = data.authorization_info;
re.ErrorMsg = "";
}
else
{
re.ErrorMsg = "缺少auth_code";
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw e;
}
return new HttpResponseMessage()
{
Content = new StringContent(JsonConvert.SerializeObject(re), Encoding.UTF8,
"application/json"),
};
}
public class ChangeTokensJob
{
public static int ExpiresIn => Convert.ToInt32(ConfigurationManager.AppSettings["TokenDate"]);
public static void token()
{
Logger.Debug(@"添加定時器並執行,每隔多少秒執行一次:" + ExpiresIn);
new QJob("systoken1", "token1", "token", "group").Handle(GetComponent_Token).Start(DateTime.Now, ExpiresIn == 0 ? 7000 : ExpiresIn, 0);
Logger.Debug(@"添加定時器完成");
}
///
/// 獲取令牌
///
private static void GetComponent_Token()
{
var re = new ApiResponseObject()
{
ErrorCode = (int)ErrorCodeEnum.Normal,
ErrorMsg = "系統出錯了",
success = false
};
try
{
var sql = string.Format(@"select * from WxComponentVerifyTicket Order by ID Desc limit 0,1");
var model = openDb.ExecuteModel
(sql);
var data = InterfaceApi.Component_token(model.ComponentVerifyTicket);
Logger.Debug("獲取Component_token成功:" + data.component_access_token + "---------" + data.expires_in);
var sqlInser =
$@"INSERT INTO WxComponentAccessToken (ComponentAccessToken,ExpiresIn) VALUES ('{data.component_access_token}',{data.expires_in});";
var retData = openDb.ExecuteNonQuery(sqlInser);
if (retData >= 1)
{
Logger.Debug("Component_token插入成功");
}
Logger.Debug("去獲取Code");
if (isAuthCode)
{
isAuthCode = false;
new QJob("sysCode1", "Code1", "Code", "CodeGroup").Handle(GetAuthCode).Start(DateTime.Now, 1700, 0);
}
}
catch (Exception ex)
{
Logger.Debug(@"獲取getComponent_token出錯:" + ex);
}
//return new HttpResponseMessage()
//{
// Content = new StringContent(JsonConvert.SerializeObject(re), Encoding.UTF8,
// "application/json"),
//};
}
///
/// 獲取Code Code有效期十分鍾
///
public static void GetAuthCode()
{
var sqlToken = string.Format(@"select * from WxComponentAccessToken Order by ID Desc limit 0,1");
var model = openDb.ExecuteModel
(sqlToken);
var code = InterfaceApi.Create_preauthcode(model.ComponentAccessToken).pre_auth_code;
Logger.Debug("成功獲取code:" + code);
QrCode(code);
}
public void ChangeTokensPeriodically()
{
}
public static void QrCode(string preAuthCode)
{
try
{
var data = InterfaceApi.GenerateQrCode(preAuthCode);
Logger.Debug("image:" + data);
}
catch (Exception e)
{
Console.WriteLine(e);
Logger.Debug("生成二維碼出錯了:" + e);
throw e;
}
}
}
源碼下載地址:
鏈接:https://pan.baidu.com/s/1ESkWbmxNvu9OkiIYpkqT1Q&shfl=sharepset
提取碼:d4e2
鏈接:
https://share.weiyun.com/5b5YCGe
(密碼:n51a)