1. 程式人生 > >微信開發筆記-調用自定義分享接口

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

彈出菜單 菜單 開發筆記 n-1 onf target ready 模式 時間戳

文章來自:http://www.cnblogs.com/ysyn/archive/2015/07/23/4665897.html

引言:

  工作中開發微信網站,簡稱微網站。由於微網站的分享內容是系統自動選取的當前網址,客戶需要改變分享的內容,即點擊屏幕右上角的分享按鈕,選擇發送給朋友和發送到朋友圈,其中的內容和圖片需要自定義。於是查找文檔微信JS-SDK說明文檔一文和網站眾多高手的經驗,大體知道了調用的步驟,但是具體如何調用才能成功卻是不了解的。經過一番試驗,終於成功調用發送朋友和發送到朋友圈兩個接口,此處記錄調用的具體過程。

步驟一:引用js文件。

在需要調用JS接口的頁面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.0.0.js

步驟二:通過config接口註入權限驗證配置

技術分享
wx.config({
    debug: true, // 開啟調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時才會打印。
    appId: ‘‘, // 必填,公眾號的唯一標識
    timestamp: , // 必填,生成簽名的時間戳
    nonceStr: ‘‘, // 必填,生成簽名的隨機串
    signature: ‘‘,// 必填,簽名,見附錄1
    jsApiList: [] // 必填,需要使用的JS接口列表,所有JS接口列表見附錄2
});
技術分享

網上眾多網友也是這樣寫的,但是具體如果配卻談之甚少,接下來介紹本文是如何調用的。

debug和appId,都不用說,很簡單。

timespan生成簽名的時間戳:

技術分享
/// <summary>
        /// 生成時間戳
        /// 從 1970 年 1 月 1 日 00:00:00 至今的秒數,即當前的時間,且最終需要轉換為字符串形式
        /// </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");
        }
技術分享 技術分享 View Code

singature簽名的生成比較麻煩。

首先生成獲取access_token(有效期7200秒,開發者必須在自己的服務全局緩存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;
        }
技術分享 技術分享 View Code

接著獲取jsapi_ticket:

用第一步拿到的access_token 采用http GET方式請求獲得jsapi_ticket(有效期7200秒,開發者必須在自己的服務全局緩存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;
        }
技術分享 技術分享 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信息驗證後會執行ready方法,所有接口調用都必須在config接口獲得結果之後,config是一個客戶端的異步操作,所以如果需要在頁面加載時就調用相關接口,則須把相關接口放在ready函數中調用來確保正確執行。對於用戶觸發時才調用的接口,則可以直接調用,不需要放在ready函數中。
});

本文的調用實例是:
技術分享
<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>
技術分享

本文基本上總結到此處。

易出現的問題:

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

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

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



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

補充:

微信網頁中長按二維碼圖片能彈出菜單是怎麽實現的?

、、

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