您好,登錄后才能下訂單哦!
這篇文章主要介紹了微信開發(fā)中如何調用自定義分享接口,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
引言:
工作中開發(fā)微信網(wǎng)站,簡稱微網(wǎng)站。由于微網(wǎng)站的分享內容是系統(tǒng)自動選取的當前網(wǎng)址,客戶需要改變分享的內容,即點擊屏幕右上角的分享按鈕,選擇發(fā)送給朋友和發(fā)送到朋友圈,其中的內容和圖片需要自定義。于是查找文檔微信JS-SDK說明文檔一文和網(wǎng)站眾多高手的經驗,大體知道了調用的步驟,但是具體如何調用才能成功卻是不了解的。經過一番試驗,終于成功調用發(fā)送朋友和發(fā)送到朋友圈兩個接口,此處記錄調用的具體過程。
步驟一:引用js文件。
在需要調用JS接口的頁面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.0.0.js
步驟二:通過config接口注入權限驗證配置
wx.config({ debug: true, // 開啟調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數(shù),可以在pc端打開,參數(shù)信息會通過log打出,僅在pc端時才會打印。 appId: '', // 必填,公眾號的唯一標識 timestamp: , // 必填,生成簽名的時間戳 nonceStr: '', // 必填,生成簽名的隨機串 signature: '',// 必填,簽名,見附錄1 jsApiList: [] // 必填,需要使用的JS接口列表,所有JS接口列表見附錄2 });
網(wǎng)上眾多網(wǎng)友也是這樣寫的,但是具體如果配卻談之甚少,接下來介紹本文是如何調用的。
debug和appId,都不用說,很簡單。
timespan生成簽名的時間戳:
/// <summary> /// 生成時間戳 /// 從 1970 年 1 月 1 日 00:00:00 至今的秒數(shù),即當前的時間,且最終需要轉換為字符串形式 /// </summary> /// <returns></returns> public string getTimestamp() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalSeconds).ToString(); }
nonceStr生成簽名的隨機串:
/// <summary> /// 生成隨機字符串 /// </summary> /// <returns></returns> public string getNoncestr() { Random random = new Random(); return MD5Util.GetMD5(random.Next(1000).ToString(), "GBK"); }
/// <summary> /// MD5Util 的摘要說明。 /// </summary> public class MD5Util { public MD5Util() { // // TODO: 在此處添加構造函數(shù)邏輯 // } /** 獲取大寫的MD5簽名結果 */ public static string GetMD5(string encypStr, string charset) { string retStr; MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider(); //創(chuàng)建md5對象 byte[] inputBye; byte[] outputBye; //使用GB2312編碼方式把字符串轉化為字節(jié)數(shù)組. try { inputBye = Encoding.GetEncoding(charset).GetBytes(encypStr); } catch (Exception ex) { inputBye = Encoding.GetEncoding("GB2312").GetBytes(encypStr); } outputBye = m5.ComputeHash(inputBye); retStr = System.BitConverter.ToString(outputBye); retStr = retStr.Replace("-", "").ToUpper(); return retStr; } }
View Code
/// <summary> /// MD5Util 的摘要說明。 /// </summary> public class MD5Util { public MD5Util() { // // TODO: 在此處添加構造函數(shù)邏輯 // } /** 獲取大寫的MD5簽名結果 */ public static string GetMD5(string encypStr, string charset) { string retStr; MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider(); //創(chuàng)建md5對象 byte[] inputBye; byte[] outputBye; //使用GB2312編碼方式把字符串轉化為字節(jié)數(shù)組. try { inputBye = Encoding.GetEncoding(charset).GetBytes(encypStr); } catch (Exception ex) { inputBye = Encoding.GetEncoding("GB2312").GetBytes(encypStr); } outputBye = m5.ComputeHash(inputBye); retStr = System.BitConverter.ToString(outputBye); retStr = retStr.Replace("-", "").ToUpper(); return retStr; } }
singature簽名的生成比較麻煩。
首先生成獲取access_token(有效期7200秒,開發(fā)者必須在自己的服務全局緩存access_token)
public string Getaccesstoken() { string appid = System.Configuration.ConfigurationManager.AppSettings["WXZjAppID"].ToString(); string secret = System.Configuration.ConfigurationManager.AppSettings["WXZjAppSecret"].ToString(); string urljson = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret; string strjson = ""; UTF8Encoding encoding = new UTF8Encoding(); HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(urljson); myRequest.Method = "GET"; myRequest.ContentType = "application/x-www-form-urlencoded"; HttpWebResponse response; Stream responseStream; StreamReader reader; string srcString; response = myRequest.GetResponse() as HttpWebResponse; responseStream = response.GetResponseStream(); reader = new System.IO.StreamReader(responseStream, Encoding.UTF8); srcString = reader.ReadToEnd(); reader.Close(); if (srcString.Contains("access_token")) { //CommonJsonModel model = new CommonJsonModel(srcString); HP.CPS.BLL.WeiXin.CommonJsonModel model = new BLL.WeiXin.CommonJsonModel(srcString); strjson = model.GetValue("access_token"); Session["access_tokenzj"] = strjson; } return strjson; }
public class CommonJsonModelAnalyzer { protected string _GetKey(string rawjson) { if (string.IsNullOrEmpty(rawjson)) return rawjson; rawjson = rawjson.Trim(); string[] jsons = rawjson.Split(new char[] { ':' }); if (jsons.Length < 2) return rawjson; return jsons[0].Replace("\"", "").Trim(); } protected string _GetValue(string rawjson) { if (string.IsNullOrEmpty(rawjson)) return rawjson; rawjson = rawjson.Trim(); string[] jsons = rawjson.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (jsons.Length < 2) return rawjson; StringBuilder builder = new StringBuilder(); for (int i = 1; i < jsons.Length; i++) { builder.Append(jsons[i]); builder.Append(":"); } if (builder.Length > 0) builder.Remove(builder.Length - 1, 1); string value = builder.ToString(); if (value.StartsWith("\"")) value = value.Substring(1); if (value.EndsWith("\"")) value = value.Substring(0, value.Length - 1); return value; } protected List<string> _GetCollection(string rawjson) { //[{},{}] List<string> list = new List<string>(); if (string.IsNullOrEmpty(rawjson)) return list; rawjson = rawjson.Trim(); StringBuilder builder = new StringBuilder(); int nestlevel = -1; int mnestlevel = -1; for (int i = 0; i < rawjson.Length; i++) { if (i == 0) continue; else if (i == rawjson.Length - 1) continue; char jsonchar = rawjson[i]; if (jsonchar == '{') { nestlevel++; } if (jsonchar == '}') { nestlevel--; } if (jsonchar == '[') { mnestlevel++; } if (jsonchar == ']') { mnestlevel--; } if (jsonchar == ',' && nestlevel == -1 && mnestlevel == -1) { list.Add(builder.ToString()); builder = new StringBuilder(); } else { builder.Append(jsonchar); } } if (builder.Length > 0) list.Add(builder.ToString()); return list; } } public class CommonJsonModel : CommonJsonModelAnalyzer { private string rawjson; private bool isValue = false; private bool isModel = false; private bool isCollection = false; public CommonJsonModel(string rawjson) { this.rawjson = rawjson; if (string.IsNullOrEmpty(rawjson)) throw new Exception("missing rawjson"); rawjson = rawjson.Trim(); if (rawjson.StartsWith("{")) { isModel = true; } else if (rawjson.StartsWith("[")) { isCollection = true; } else { isValue = true; } } public string Rawjson { get { return rawjson; } } public bool IsValue() { return isValue; } public bool IsValue(string key) { if (!isModel) return false; if (string.IsNullOrEmpty(key)) return false; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) { CommonJsonModel submodel = new CommonJsonModel(model.Value); return submodel.IsValue(); } } return false; } public bool IsModel() { return isModel; } public bool IsModel(string key) { if (!isModel) return false; if (string.IsNullOrEmpty(key)) return false; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) { CommonJsonModel submodel = new CommonJsonModel(model.Value); return submodel.IsModel(); } } return false; } public bool IsCollection() { return isCollection; } public bool IsCollection(string key) { if (!isModel) return false; if (string.IsNullOrEmpty(key)) return false; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) { CommonJsonModel submodel = new CommonJsonModel(model.Value); return submodel.IsCollection(); } } return false; } /// <summary> /// 當模型是對象,返回擁有的key /// </summary> /// <returns></returns> public List<string> GetKeys() { if (!isModel) return null; List<string> list = new List<string>(); foreach (string subjson in base._GetCollection(this.rawjson)) { string key = new CommonJsonModel(subjson).Key; if (!string.IsNullOrEmpty(key)) list.Add(key); } return list; } /// <summary> /// 當模型是對象,key對應是值,則返回key對應的值 /// </summary> /// <param name="key"></param> /// <returns></returns> public string GetValue(string key) { if (!isModel) return null; if (string.IsNullOrEmpty(key)) return null; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) return model.Value; } return null; } /// <summary> /// 模型是對象,key對應是對象,返回key對應的對象 /// </summary> /// <param name="key"></param> /// <returns></returns> public CommonJsonModel GetModel(string key) { if (!isModel) return null; if (string.IsNullOrEmpty(key)) return null; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) { CommonJsonModel submodel = new CommonJsonModel(model.Value); if (!submodel.IsModel()) return null; else return submodel; } } return null; } /// <summary> /// 模型是對象,key對應是集合,返回集合 /// </summary> /// <param name="key"></param> /// <returns></returns> public CommonJsonModel GetCollection(string key) { if (!isModel) return null; if (string.IsNullOrEmpty(key)) return null; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) { CommonJsonModel submodel = new CommonJsonModel(model.Value); if (!submodel.IsCollection()) return null; else return submodel; } } return null; } /// <summary> /// 模型是集合,返回自身 /// </summary> /// <returns></returns> public List<CommonJsonModel> GetCollection() { List<CommonJsonModel> list = new List<CommonJsonModel>(); if (IsValue()) return list; foreach (string subjson in base._GetCollection(rawjson)) { list.Add(new CommonJsonModel(subjson)); } return list; } /// <summary> /// 當模型是值對象,返回key /// </summary> private string Key { get { if (IsValue()) return base._GetKey(rawjson); return null; } } /// <summary> /// 當模型是值對象,返回value /// </summary> private string Value { get { if (!IsValue()) return null; return base._GetValue(rawjson); } } }
View Code
public class CommonJsonModelAnalyzer { protected string _GetKey(string rawjson) { if (string.IsNullOrEmpty(rawjson)) return rawjson; rawjson = rawjson.Trim(); string[] jsons = rawjson.Split(new char[] { ':' }); if (jsons.Length < 2) return rawjson; return jsons[0].Replace("\"", "").Trim(); } protected string _GetValue(string rawjson) { if (string.IsNullOrEmpty(rawjson)) return rawjson; rawjson = rawjson.Trim(); string[] jsons = rawjson.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (jsons.Length < 2) return rawjson; StringBuilder builder = new StringBuilder(); for (int i = 1; i < jsons.Length; i++) { builder.Append(jsons[i]); builder.Append(":"); } if (builder.Length > 0) builder.Remove(builder.Length - 1, 1); string value = builder.ToString(); if (value.StartsWith("\"")) value = value.Substring(1); if (value.EndsWith("\"")) value = value.Substring(0, value.Length - 1); return value; } protected List<string> _GetCollection(string rawjson) { //[{},{}] List<string> list = new List<string>(); if (string.IsNullOrEmpty(rawjson)) return list; rawjson = rawjson.Trim(); StringBuilder builder = new StringBuilder(); int nestlevel = -1; int mnestlevel = -1; for (int i = 0; i < rawjson.Length; i++) { if (i == 0) continue; else if (i == rawjson.Length - 1) continue; char jsonchar = rawjson[i]; if (jsonchar == '{') { nestlevel++; } if (jsonchar == '}') { nestlevel--; } if (jsonchar == '[') { mnestlevel++; } if (jsonchar == ']') { mnestlevel--; } if (jsonchar == ',' && nestlevel == -1 && mnestlevel == -1) { list.Add(builder.ToString()); builder = new StringBuilder(); } else { builder.Append(jsonchar); } } if (builder.Length > 0) list.Add(builder.ToString()); return list; } } public class CommonJsonModel : CommonJsonModelAnalyzer { private string rawjson; private bool isValue = false; private bool isModel = false; private bool isCollection = false; public CommonJsonModel(string rawjson) { this.rawjson = rawjson; if (string.IsNullOrEmpty(rawjson)) throw new Exception("missing rawjson"); rawjson = rawjson.Trim(); if (rawjson.StartsWith("{")) { isModel = true; } else if (rawjson.StartsWith("[")) { isCollection = true; } else { isValue = true; } } public string Rawjson { get { return rawjson; } } public bool IsValue() { return isValue; } public bool IsValue(string key) { if (!isModel) return false; if (string.IsNullOrEmpty(key)) return false; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) { CommonJsonModel submodel = new CommonJsonModel(model.Value); return submodel.IsValue(); } } return false; } public bool IsModel() { return isModel; } public bool IsModel(string key) { if (!isModel) return false; if (string.IsNullOrEmpty(key)) return false; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) { CommonJsonModel submodel = new CommonJsonModel(model.Value); return submodel.IsModel(); } } return false; } public bool IsCollection() { return isCollection; } public bool IsCollection(string key) { if (!isModel) return false; if (string.IsNullOrEmpty(key)) return false; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) { CommonJsonModel submodel = new CommonJsonModel(model.Value); return submodel.IsCollection(); } } return false; } /// <summary> /// 當模型是對象,返回擁有的key /// </summary> /// <returns></returns> public List<string> GetKeys() { if (!isModel) return null; List<string> list = new List<string>(); foreach (string subjson in base._GetCollection(this.rawjson)) { string key = new CommonJsonModel(subjson).Key; if (!string.IsNullOrEmpty(key)) list.Add(key); } return list; } /// <summary> /// 當模型是對象,key對應是值,則返回key對應的值 /// </summary> /// <param name="key"></param> /// <returns></returns> public string GetValue(string key) { if (!isModel) return null; if (string.IsNullOrEmpty(key)) return null; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) return model.Value; } return null; } /// <summary> /// 模型是對象,key對應是對象,返回key對應的對象 /// </summary> /// <param name="key"></param> /// <returns></returns> public CommonJsonModel GetModel(string key) { if (!isModel) return null; if (string.IsNullOrEmpty(key)) return null; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) { CommonJsonModel submodel = new CommonJsonModel(model.Value); if (!submodel.IsModel()) return null; else return submodel; } } return null; } /// <summary> /// 模型是對象,key對應是集合,返回集合 /// </summary> /// <param name="key"></param> /// <returns></returns> public CommonJsonModel GetCollection(string key) { if (!isModel) return null; if (string.IsNullOrEmpty(key)) return null; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) { CommonJsonModel submodel = new CommonJsonModel(model.Value); if (!submodel.IsCollection()) return null; else return submodel; } } return null; } /// <summary> /// 模型是集合,返回自身 /// </summary> /// <returns></returns> public List<CommonJsonModel> GetCollection() { List<CommonJsonModel> list = new List<CommonJsonModel>(); if (IsValue()) return list; foreach (string subjson in base._GetCollection(rawjson)) { list.Add(new CommonJsonModel(subjson)); } return list; } /// <summary> /// 當模型是值對象,返回key /// </summary> private string Key { get { if (IsValue()) return base._GetKey(rawjson); return null; } } /// <summary> /// 當模型是值對象,返回value /// </summary> private string Value { get { if (!IsValue()) return null; return base._GetValue(rawjson); } } }
接著獲取jsapi_ticket:
用第一步拿到的access_token 采用http GET方式請求獲得jsapi_ticket(有效期7200秒,開發(fā)者必須在自己的服務全局緩存jsapi_ticket)
public string Getjsapi_ticket() { string accesstoken = (string)Session["access_tokenzj"]; string urljson = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accesstoken + "&type=jsapi"; string strjson = ""; UTF8Encoding encoding = new UTF8Encoding(); HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(urljson); myRequest.Method = "GET"; myRequest.ContentType = "application/x-www-form-urlencoded"; HttpWebResponse response = myRequest.GetResponse() as HttpWebResponse; Stream responseStream = response.GetResponseStream(); StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8); string srcString = reader.ReadToEnd(); reader.Close(); if (srcString.Contains("ticket")) { HP.CPS.BLL.WeiXin.CommonJsonModel model = new BLL.WeiXin.CommonJsonModel(srcString); strjson = model.GetValue("ticket"); Session["ticketzj"] = strjson; } return strjson; }
最后生成signature:
public string Getsignature(string nonceStr, string timespanstr) { if (Session["access_tokenzj"] == null) { Getaccesstoken(); } if (Session["ticketzj"] == null) { Getjsapi_ticket(); } string url = Request.Url.ToString(); string str = "jsapi_ticket=" + (string)Session["ticketzj"] + "&noncestr=" + nonceStr + "×tamp=" + timespanstr + "&url=" + url;// +"&wxref=mp.weixin.qq.com"; string singature = SHA1Util.getSha1(str); string ss = singature; return ss; }
class SHA1Util { public static String getSha1(String str) { //建立SHA1對象 SHA1 sha = new SHA1CryptoServiceProvider(); //將mystr轉換成byte[] ASCIIEncoding enc = new ASCIIEncoding(); byte[] dataToHash = enc.GetBytes(str); //Hash運算 byte[] dataHashed = sha.ComputeHash(dataToHash); //將運算結果轉換成string string hash = BitConverter.ToString(dataHashed).Replace("-", ""); return hash; } }
class SHA1Util { public static String getSha1(String str) { //建立SHA1對象 SHA1 sha = new SHA1CryptoServiceProvider(); //將mystr轉換成byte[] ASCIIEncoding enc = new ASCIIEncoding(); byte[] dataToHash = enc.GetBytes(str); //Hash運算 byte[] dataHashed = sha.ComputeHash(dataToHash); //將運算結果轉換成string string hash = BitConverter.ToString(dataHashed).Replace("-", ""); return hash; } }
View Code
本文調用實例:
<script type="text/javascript"> wx.config({ debug: false, appId: '<%=corpid %>', timestamp: <%=timestamp%>, nonceStr: '<%=nonceStr%>', signature: '<%=signature %>', jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'] }); </script>
步驟三:調用接口
在進行完第二步的調用后,步驟三就顯得非常輕巧了。
wx.ready(function(){ // config信息驗證后會執(zhí)行ready方法,所有接口調用都必須在config接口獲得結果之后,config是一個客戶端的異步操作,所以如果需要在頁面加載時就調用相關接口,則須把相關接口放在ready函數(shù)中調用來確保正確執(zhí)行。對于用戶觸發(fā)時才調用的接口,則可以直接調用,不需要放在ready函數(shù)中。});
本文的調用實例是:
<script type="text/javascript" > wx.ready(function () { wx.onMenuShareAppMessage({ title: '<%=shareTitle %>', desc: '<%=shareContent %>', link: '<%=currentUrl %>', imgUrl: '<%=shareImageUrl %>' }); wx.onMenuShareTimeline({ title: '<%=shareContent %>', link: '<%=currentUrl %>', imgUrl: '<%=shareImageUrl %>' }); }) </script>
<script type="text/javascript" > wx.ready(function () { wx.onMenuShareAppMessage({ title: '<%=shareTitle %>', desc: '<%=shareContent %>', link: '<%=currentUrl %>', imgUrl: '<%=shareImageUrl %>' }); wx.onMenuShareTimeline({ title: '<%=shareContent %>', link: '<%=currentUrl %>', imgUrl: '<%=shareImageUrl %>' }); }) </script>
感謝你能夠認真閱讀完這篇文章,希望小編分享的“微信開發(fā)中如何調用自定義分享接口”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業(yè)資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。