国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

微信開發(fā)筆記-調用自定義分享接口

2019-11-14 15:54:01
字體:
來源:轉載
供稿:網(wǎng)友

引言:

  工作中開發(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

 

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

 

接著獲取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 +                "&timestamp=" + 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;        }    }
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>

本文基本上總結到此處。

易出現(xiàn)的問題:

1、檢查后臺是否設置:右上角公眾號名稱--功能設置--JS接口安全域名

2、檢查代碼里的appid和公眾號后臺的id是否一致

3、圖片的調用地址是絕對路徑(相對路徑好像不行)。



引用文檔:
微信JS-SDK說明文檔

 


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 宁波市| 三江| 临泽县| 蓬安县| 宣汉县| 铁岭县| 无为县| 吉林省| 安达市| 万州区| 泾源县| 庆阳市| 安多县| 芒康县| 乌拉特中旗| 江达县| 休宁县| 韶山市| 兴城市| 砀山县| 林州市| 大厂| 确山县| 伊宁市| 托里县| 富川| 盈江县| 吴忠市| 若尔盖县| 盐边县| 宜都市| 柘城县| 偃师市| 东海县| 青河县| 丰镇市| 宿迁市| 白山市| 兴山县| 大丰市| 新绛县|