【微信公衆號開發】獲取並保存access_token、jsapi_ticket票據(可用於微信分享、語音識別等等)

 

步驟一:首先得開通公衆號(目的是 得到appid、AppSecret、設置安全域名)~javascript

 

【公衆號設置】→【功能設置】 設置相應的域名html

 

步驟二:編寫幫助類WeixinLuyinHelper中的代碼java

#region 請求Url,不發送數據
/// <summary>
/// 請求Url,不發送數據
/// </summary>
public static string RequestUrl(string url)
{
return RequestUrl(url, "POST");
}
#endregionjquery


#region 請求Url,不發送數據
/// <summary>
/// 請求Url,不發送數據
/// </summary>
public static string RequestUrl(string url, string method)
{
// 設置參數
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = method;
request.ContentType = "text/html";
request.Headers.Add("charset", "utf-8");json

//發送請求並獲取相應迴應數據
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序纔開始向目標網頁發送Post請求
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
//返回結果網頁(html)代碼
string content = sr.ReadToEnd();
return content;
}
#endregionapi

 

#region 獲取Json字符串某節點的值
/// <summary>
/// 獲取Json字符串某節點的值
/// </summary>
public static string GetJsonValue(string jsonStr, string key)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(jsonStr))
{
key = "\"" + key.Trim('"') + "\"";
int index = jsonStr.IndexOf(key) + key.Length + 1;
if (index > key.Length + 1)
{
//先截逗號,如果最後一個,截「}」號,取最小值
int end = jsonStr.IndexOf(',', index);
if (end == -1)
{
end = jsonStr.IndexOf('}', index);
}安全

result = jsonStr.Substring(index, end - index);
result = result.Trim(new char[] { '"', ' ', '\'' }); //過濾引號或空格
}
}
return result;
}
#endregion微信

 

#region獲取access_token
/// <summary>
/// 獲取Token
/// </summary>
public static string GetToken(string appid, string secret)
{
string strJson = RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret));
return GetJsonValue(strJson, "access_token");
}
#endregioncookie

 

#region 獲取jsapi_ticket
/// <summary>
/// 獲取Token
/// </summary>
public static string Getjsapi_ticketToken(string access_token)
{
string strJson = RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", access_token));
return GetJsonValue(strJson, "ticket");
}
#endregionapp

 

#region 生成簽名
public static SignatureModel GetSignature(string jsapi_ticket)
{
var timestamp = GetTimeStamp();
var noncestr = new Random().Next(10000).ToString();
var uri = "http://m.wanwushuo.com/Home/WeixinLuyin";
string oldstr = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + uri;

byte[] cleanBytes = Encoding.UTF8.GetBytes(oldstr);
byte[] hashedBytes = System.Security.Cryptography.SHA1.Create().ComputeHash(cleanBytes);

string newstr= BitConverter.ToString(hashedBytes).Replace("-", "");
SignatureModel SignatureModel = new SignatureModel();
SignatureModel.noncestr=noncestr;
SignatureModel.Signature=newstr;
SignatureModel.timestamp=timestamp;
return SignatureModel;

}

#endregion

 

 

步驟三:調用上面方法便可(根據第一步上面得到的appid、AppSecret  獲取access_token、jsapi_ticket 生成Signature簽名

string AppID = "999999999";
string AppSecret = "8888888888";

獲取access_token 
string access_token = WeixinLuyinHelper.GetToken(AppID, AppSecret);//

獲取jsapi_ticket

string jsapi_ticket = WeixinLuyinHelper.Getjsapi_ticketToken(access_token);

生成Signature簽名
SignatureModel SignatureModel = WeixinLuyinHelper.GetSignature(jsapi_ticket);

 

 

應用:接下來就比較簡單了 拿到簽名Signature 可用於微信分享、語音識別、微信掃一掃、搖一搖等 

下面以微信分享爲例:

頁面

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>WeixinLuyin</title>
</head>
<body>
<div>


</div>

<script src="~/Scripts/jquery.js"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script type="text/javascript">

//配置config appid signature等剛纔已經得到了 傳到這邊便可

wx.config({
debug: true, // 開啓調試模式,調用的全部api的返回值會在客戶端alert出來,若要查看傳入的參數,能夠在pc端打開,參數信息會經過log打出,僅在pc端時纔會打印。
appId: "@Model.AppID", // 必填,公衆號的惟一標識
timestamp:"@Model.timestamp" , // 必填,生成簽名的時間戳
nonceStr: "@Model.noncestr", // 必填,生成簽名的隨機串
signature: "@Model.Signature",// 必填,簽名,見附錄1
jsApiList: ["onMenuShareTimeline"] // 必填,須要使用的JS接口列表,全部JS接口列表見附錄2(此處填寫了分享的接口)
});

wx.ready(function () {

//在這裏調用分享接口

wx.onMenuShareTimeline({

    title: '', // 分享標題

    link: '', // 分享連接

    imgUrl: '', // 分享圖標

    success: function () { 

        // 用戶確認分享後執行的回調函數

    },

    cancel: function () { 

        // 用戶取消分享後執行的回調函數

    }

});

});

 

</script>
</body>
</html>

 

 

OVER 本文到這裏介紹 內容簡單 給沒接觸或剛接觸微信公衆號開發的鮮肉看看 大神繞行  有問題請留言

 

相關文章
相關標籤/搜索