微信內置瀏覽器 用 JS 調用微信APP分享到微信朋友圈

   昨天開始搞分享到微信朋友圈,要求直接調用微信APP的分享到朋友圈。。。

   1:首先你需要完成微信的六大前期準備工作,這也是最煩人的。請仔細閱讀微信的APP文檔:

   文檔地址:https://mp.weixin.qq.com/wiki/11/74ad127cc054f6b80759c40f77ec03db.html

  

   


  1.1  綁定域名 這種東西,需要註冊,需要實名制,還不能註冊爲個人模式,要不不給接口使用權限,請注意...

         最終的要是你需要 有域名,還有獲取 微信給你的2個 值 ,AppId 和 AppSecret

  1.2, 這個簡單,看文檔就好

  1.3:這個按照他的方式 ,我實現的代碼如下:緩存什麼的我就沒寫了,因爲只是Demo,jsapi_ticket每天只能獲取2000次,如果你只是研發應該夠用

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace HuaSharp.SunCms.WebSite.RongYM
{
    public partial class wxTest : System.Web.UI.Page
    {

        //公衆號ID,爲了獲取還需要拿自己的微信去註冊,各種驗證實名制,尼瑪真麻煩
        public static string AppId = "wxea8cd26d4b77ebd9";
        //公衆號的密鑰 ,註冊後各種操作登錄後獲得.
        public static string AppSecret = "01187a13372d431a398458ec49b77a10";

        //全局緩存對象  有效時間 2小時   微信JS接口的臨時票據
        public static string jsapi_ticket = "";

        //用它來獲取  jsapi_ticket ,它的有效期也是2小時,開發者必須在自己的服務全局緩存access_token , 它的值是通過接口獲得的.
        //access_token是公衆號的全局唯一票據,公衆號調用各接口時都需使用access_token
        //access_token的有效時間可能會在未來有調整,所以中控服務器不僅需要內部定時主動刷新,還需要提供被動刷新access_token的接口,這樣便於業務服務器在API調用獲知access_token已超時的情況下,可以觸發access_token的刷新流程
        public static string access_token = "";

        //傻逼微信還需要傳入時間撮來完成它的機密算法 
        public static string timestamp = "";

        //傻逼微信還需要傳入當前頁面的url來完成它的加密算法
        public static string curUrl = "";

        //尼瑪,還需要一個隨機串,來給它完成加密驗證,噁心死了
        public static string noncestr = "zyq";

        //上面那麼多垃圾東西,那麼多次訪問httpget,那麼多次緩存,就是爲了這個垃圾簽名.
        public static string signature = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            // access_token = "nC_O_2yUvP0CEcstb2wfTpP-zEOfJEyggcEWvrwAO1sO8H1TRpgjCJBmOPqCepcUOz64r0SKI8UTSSgY5Y8tmicCMZ3MKaATYVwppHXOiwmWOTImxDkIUMx1GEoO3MkaGDZfAEAURN";
            if (string.IsNullOrWhiteSpace(access_token))
            {   //獲取access_token
                string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + AppId + "&secret=" + AppSecret;
                string result = GetHttp(url, this.Context);

                wxApiModel xwapi = JsonToObj(result, typeof(wxApiModel)) as wxApiModel;
                access_token = xwapi.access_token;
                //{ "access_token":"RlUQfwT7ALMEhpd7d-lwwdVl1L-shnlpR0f52dZdGTgETMXDik6kSlbsn0YywWDyt2DhcUo7bprg6lpfuCrdF3tDFlUrpj8Gt17jnuTxNBmW0HzTa7HWxYqLzX7AayvVPFSgAIADTG","expires_in":7200}
            }

            // jsapi_ticket = "kgt8ON7yVITDhtdwci0qeRexnVHaoFgZBri5CQ_FeuE26sRqPoRdqWba5z2zCcjWdvw70MKC3YJAvK9ieHSo7w";
            //用第一步拿到的access_token 採用http GET方式請求獲得jsapi_ticket
            if (string.IsNullOrWhiteSpace(jsapi_ticket))
            {
                string url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";
                string result = GetHttp(url, this.Context);
                wxApiModel xwapi = JsonToObj(result, typeof(wxApiModel)) as wxApiModel;

                jsapi_ticket = xwapi.ticket;
                //{
                //    "errcode": 0,
                //    "errmsg": "ok",
                //    "ticket": "kgt8ON7yVITDhtdwci0qeRexnVHaoFgZBri5CQ_FeuHhRjNuvsKJ2ewt9V8iAZa2aorvGWgaPOgJkmRG442DZg",
                //    "expires_in": 7200
                //}
            }

            timestamp = GenerateTimeStamp();

            curUrl = this.Request.Url.ToString();
            //string param = "jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW×tamp=1414587457&url=http://mp.weixin.qq.com?params=value";
            string param = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url=" + curUrl;
            //通過SHA1加密算法獲得簽名
            signature = FormsAuthentication.HashPasswordForStoringInConfigFile(param, "SHA1");
        }


        public static string GetHttp(string url, HttpContext httpContext)
        {

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "GET";
            httpWebRequest.Timeout = 20000;

            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            string responseContent = streamReader.ReadToEnd();

            httpWebResponse.Close();
            streamReader.Close();

            return responseContent;
        }

        /// <summary>
        /// 獲取時間撮
        /// </summary>
        /// <returns></returns>
        public static string GenerateTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        /// <summary>
        /// 把JSON 格式 轉換成List<Model>
        /// </summary>
        /// <param name="json"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public static Object JsonToObj(String json, Type t)
        {
            try
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(t);
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
                {
                    return serializer.ReadObject(ms);
                }
            }
            catch
            {
                return null;
            }
        }

    }

    public class wxApiModel
    {
        public string access_token { get; set; }

        public string expires_in { get; set; }

        public string errcode { get; set; }

        public string errmsg { get; set; }

        public string ticket { get; set; }
    }
}


然後前臺代碼如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="wxTest.aspx.cs" Inherits="HuaSharp.SunCms.WebSite.RongYM.wxTest" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
    <script type="text/javascript">
        
           wx.config({
                debug: true, // 開啓調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時纔會打印。
                appId: '<%=AppId%>', // 必填,公衆號的唯一標識
                timestamp: <%=timestamp%>, // 必填,生成簽名的時間戳
                nonceStr: '<%=noncestr%>', // 必填,生成簽名的隨機串
                signature: '<%=signature%>',// 必填,簽名,見附錄1
                jsApiList: ['onMenuShareTimeline'] // 必填,需要使用的JS接口列表,所有JS接口列表見附錄2  onMenuShareTimeline =微信分享到朋友圈,APi地址:
           });

        window.onload=function(){ 

            alert("當前域名是:<%=curUrl%>");
        }



        wx.ready(function(){
            alert("微信接口初始化完成");
            // config信息驗證後會執行ready方法,所有接口調用都必須在config接口獲得結果之後,config是一個客戶端的異步操作,所以如果需要在頁面加載時就調用相關接口,則須把相關接口放在ready函數中調用來確保正確執行。對於用戶觸發時才調用的接口,則可以直接調用,不需要放在ready函數中。
        });

        wx.error(function(res){

            alert("微信接口初始化失敗;錯誤信息:"+res);
            // config信息驗證失敗會執行error函數,如簽名過期導致驗證失敗,具體錯誤信息可以打開config的debug模式查看,也可以在返回的res參數中查看,對於SPA可以在這裏更新簽名。

        });


        function Demo()
        {
            //alert("123");
            wx.checkJsApi({
                jsApiList: ['onMenuShareTimeline'], // 需要檢測的JS接口列表,所有JS接口列表見附錄2,
                success: function(res) {
                    alert(res);
                    debugger;
                    // 以鍵值對的形式返回,可用的api值true,不可用爲false
                    // 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
                }
            });
        }

        function Demo2()
        {
            wx.onMenuShareTimeline({
                debug: true,
                title: '微信測試分享', // 分享標題
                link: 'http://rym.huasharp.com/RongYM/wxTest.aspx', // 分享鏈接
                imgUrl: 'http://rym.huasharp.com/UploadFiles/20170414111448.jpg', // 分享圖標
                success: function () { 
                    // 用戶確認分享後執行的回調函數
                    alert("分享成功");
                },
                cancel: function () { 
                    // 用戶取消分享後執行的回調函數
                    alert("分享失敗");
                },
                complete:function()
                {
                    alert("complete:接口調用完成時執行的回調函數,無論成功或失敗都會執行。");
                }
            });

            //alert('已註冊獲取“分享到朋友圈”狀態事件');
        }
        
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" style=" width;200px;height:200px " value="微信測試" onclick="Demo()"/>
        <input type="button" style=" width;200px;height:200px "  value="微信朋友圈測試" onclick="Demo2()"/>


    </div>
           <input type="button" style=" width;200px;height:200px " class="btn btn_primary" id="onMenuShareTimeline" value="onMenuShareTimeline"></input>
    </form>
</body>
</html>


然後 就可以運行了,在這裏我要告訴大家千萬要注意的地方

1:有一個比較好的測試工具,在你登錄微信公衆平臺以後,在左邊導航有個開發者工具,記得去使用


2:接口權限:正式環境的話,這些接口權限是需要開通的.當然是企業類型的賬號,開通以後的樣子是這樣的:



3:看到第2點是不是怕了?沒關係,如果你是開發者的話,在開發工具中有一個測試賬號,它擁有大部分權限:



4:測試賬號需要注意的地方(你需要有域名,並且在有域名的機器上調試最後一部分,怕了吧?微信的要求就是這麼嚴格,還有注意事項請看圖片)



5:請使用微信模擬開發工具,如果你不怕麻煩,用手機直接測試也是可以的.不過功能沒這個強大,下載地址在開發者工具裏面,具體可以參考這個百度經驗:

http://jingyan.baidu.com/article/77b8dc7f9d341f6174eab6ee.html


6:微信接口調用成功以後會有errMess提示,千萬被err這幾個字給迷惑住,其實是成功了,還有可能會保域名無效錯誤,這個你需要檢查你的域名。




7: 微信分享朋友圈執行了以後,並不是直接調用打開微信app,而是還是需要手動點擊右上角的分享.感覺功能真的是弱爆了,搞了這麼久。建議大家初始化以後,用戶點擊分享按鈕以後,你提示他使用右上角,初始化分享朋友圈和不分享的區別可以見下圖:


這個是沒有初始化設置朋友圈分享的頁面




8:到這裏就結束了,分享成功以後,會有回調方法,我發現我的iphone7 不支持。但是安卓機是支持的....無語了,最後希望微信越做越好。功能越來越強大,不像現在這麼麻煩。。。還有這裏用的是微信內置瀏覽器,微信內置瀏覽器就是說在微信中點擊鏈接,打開的瀏覽器...好弱... 因爲蘋果的不開源,蘋果上很多瀏覽器都不支持...UC瀏覽器還算支持分享到朋友圈的.

有問題可以加我QQ 10200454 詢問,我也被這個坑了一天...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章