WeixinAccount.cs
3.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using System;
namespace WeixinApi
{
/// <summary>
/// 微信公众号信息
/// </summary>
public class WeixinAccount
{
public delegate void AccessTokenCallback(WeixinAccount account);
public event AccessTokenCallback TokenRefresh;
protected virtual void OnTokenRefresh(WeixinAccount account)
{
var handler = TokenRefresh;
if (handler != null) handler(this);
}
/// <summary>
/// jsapi_ticket
/// </summary>
private string jsapi_ticket;
/// <summary>
/// access_token
/// </summary>
private string access_token;
/// <summary>
/// jsapi_ticket到期时间
/// </summary>
private DateTime jsapi_ticket_time;
/// <summary>
/// access_token到期时间
/// </summary>
private DateTime access_token_time;
/// <summary>
/// 公众号名称
/// </summary>
public string Id { get; set; }
public string AppId { get; set; }
public string AppSecret { get; set; }
public string JsapiTicket
{
get
{
if (jsapi_ticket_time < DateTime.Now)
{
var ticket = WeixinAction.GetJsapiTicket(AccessToken);
if (ticket == null || ticket.ErrorCode != 0) return string.Empty;
jsapi_ticket = ticket.Ticket;
jsapi_ticket_time = DateTime.Now.AddSeconds(ticket.ExpiresIn-200);
}
return jsapi_ticket;
}
}
public string AccessToken
{
get
{
if (access_token_time < DateTime.Now)
{
var token = WeixinAction.GetWeixinToken(AppId, AppSecret);
if (token == null) return string.Empty;
access_token = token.AccessToken;
access_token_time = DateTime.Now.AddSeconds(token.ExpiresIn-200);//token.ExpiresIn
OnTokenRefresh(this);
}
return access_token;
}
}
/// <summary>
/// 实例化微信公众号
/// </summary>
/// <param name="id"></param>
/// <param name="appid"></param>
/// <param name="secret"></param>
public WeixinAccount(string id, string appid, string secret)
{
Id = id;
AppId = appid;
AppSecret = secret;
access_token_time = DateTime.Parse("1970-01-01");
jsapi_ticket_time = DateTime.Parse("1970-01-01");
}
public WeixinAccount(string id, string appid, string secret,DateTime accesstokentime,DateTime jsapitickettime)
{
Id = id;
AppId = appid;
AppSecret = secret;
access_token_time = accesstokentime;
jsapi_ticket_time = jsapitickettime;
}
public void Update(string appid, string secret)
{
if (AppId != appid || AppSecret != secret)
{
AppId = appid;
AppSecret = secret;
access_token_time = DateTime.Parse("1970-01-01");
jsapi_ticket_time = DateTime.Parse("1970-01-01");
}
}
}
}