JS-SDK接口是什麼?php
爲了方便開發者實現微信內的網頁(基於微信瀏覽器訪問的網頁)功能,好比拍照、選圖、語音、位置等手機系統的能力,並方便開發者直接使用微信分享、掃一掃等微信特有的能力,微信推出了JS-SDK的總體開發包,供開發者方便使用。前端
分享功能java
官方文檔裏提供了php、java、node.js以及python的示例代碼,惟獨沒有c#版的,爲了彌補廣大.net用戶的需求,我把php版本的示例代碼邏輯照搬成了.net版,並在網頁前端中加入了分享功能,但願對你們有用。node
程序實現python
流程圖git
程序裏關鍵的類是JSSDK,裏面包含服務端請求認證的全部邏輯過程,下面是過程的流github
關鍵代碼分析json
爲保證第三方服務器與微信服務器之間數據傳輸的安全性,全部微信接口採用https方式調用,因此.net裏引用了比較高版本(.Net 4.5+)的網絡包進行http請求。c#
private
string
httpGet(
string
url)
{
if
(url.StartsWith(
"https"
))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpClient httpClient =
new
HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(
new
MediaTypeWithQualityHeaderValue(
"application/json"
));
HttpResponseMessage response = httpClient.GetAsync(url).Result;
if
(response.IsSuccessStatusCode)
{
string
result = response.Content.ReadAsStringAsync().Result;
return
result;
}
return
null
;
}
private
string
getAccessToken()
{
string
accessToken =
string
.Empty;
var data = JObject.Parse(getAspxFile(
"access_token.aspx"
, ASPX_HEAD[1]));
if
(data !=
null
&&
long
.Parse(data[
"expire_time"
].ToString()) < Utils.ConvertTimeStamp(DateTime.Now))
{
+
this
.appId +
"&secret="
+
this
.appSecret;
var jRes = JObject.Parse(httpGet(url));
accessToken = jRes[
"access_token"
].ToString();
if
(!
string
.IsNullOrEmpty(accessToken))
{
data[
"expire_time"
] = Utils.ConvertTimeStamp(
new
DateTime()) + 7000;
data[
"access_token"
] = accessToken;
setAspxFile(
"access_token.aspx"
, data.ToString(), ASPX_HEAD[1]);
}
}
else
accessToken = data[
"access_token"
].ToString();
return
accessToken;
}
private
string
getJsApiTicket()
{
string
ticket =
string
.Empty;
var data = JObject.Parse(getAspxFile(
"jsapi_ticket.aspx"
, ASPX_HEAD[0]));
if
(data !=
null
&&
long
.Parse(data[
"expire_time"
].ToString()) < Utils.ConvertTimeStamp(DateTime.Now))
{
string
accessToken = getAccessToken();
+ accessToken;
var jRes = JObject.Parse(httpGet(url));
ticket = jRes[
"ticket"
].ToString();
if
(!
string
.IsNullOrEmpty(ticket))
{
data[
"expire_time"
] = Utils.ConvertTimeStamp(
new
DateTime()) + 7000;
data[
"jsapi_ticket"
] = ticket;
setAspxFile(
"jsapi_ticket.aspx"
, data.ToString(), ASPX_HEAD[0]);
}
}
else
ticket = data[
"jsapi_ticket"
].ToString();
return
ticket;
}