微信公眾平臺開發(fā)—微信JS-SDK

簡介

微信JS-SDK是微信公眾平臺面向網頁開發(fā)者提供的基于微信內的網頁開發(fā)工具包。簡而言之,便是可以在第三方的網頁上按照特定的規(guī)則來調用這些js接口,網頁開發(fā)者可借助微信高效地使用拍照、選圖、語音、位置等手機系統(tǒng)的能力,同時可以直接使用微信分享、掃一掃、卡券、支付等微信特有的能力。

使用步驟

  • 綁定域名
    直接填寫www.xxx.com之類的域名,不用加 http:// ,否則在后續(xù)的測試中可能會出現(xiàn)invalid url domain的問題。
  • 引入JS文件
  • 通過config接口注入權限驗證配置
  • 通過ready接口處理成功驗證
  • 通過error接口處理失敗驗證

詳情:微信JS-SDK說明文檔

接口說明(僅介紹本文用到的兩個接口)

  • 獲取“分享到朋友圈”按鈕點擊狀態(tài)及自定義分享內容接口
wx.onMenuShareTimeline({
    title: '', // 分享標題
    link: '', // 分享鏈接
    imgUrl: '', // 分享圖標
    success: function () { 
        // 用戶確認分享后執(zhí)行的回調函數(shù)
    },
    cancel: function () { 
        // 用戶取消分享后執(zhí)行的回調函數(shù)
    }
});
  • 獲取“分享給朋友”按鈕點擊狀態(tài)及自定義分享內容接口
wx.onMenuShareAppMessage({
    title: '', // 分享標題
    desc: '', // 分享描述
    link: '', // 分享鏈接
    imgUrl: '', // 分享圖標
    type: '', // 分享類型,music、video或link,不填默認為link
    dataUrl: '', // 如果type是music或video,則要提供數(shù)據(jù)鏈接,默認為空
    success: function () { 
        // 用戶確認分享后執(zhí)行的回調函數(shù)
    },
    cancel: function () { 
        // 用戶取消分享后執(zhí)行的回調函數(shù)
    }
});
  • 注意
    需仔細閱讀:JS-SDK使用權限簽名算法
    本人在測試過程中出現(xiàn)invalid signature的錯誤,原因是簽名用的url必須是調用JS接口頁面的完整URL

示例代碼

說明:使用的是thinkphp框架
視圖index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport" content="initial-scale=1.0;width=device-width" />
    <meta http-equiv="content" content="text/html; charset=utf-8" />
    <title>微信公眾平臺開發(fā)JS-SDK</title>
    <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
    <!-- 引入微信提供的js文件 -->
</head>
<body>
    hello world!
    <script>
        wx.config({
            debug: true, // 開啟調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數(shù),可以在pc端打開,參數(shù)信息會通過log打出,僅在pc端時才會打印。
            appId: '填寫公眾號的appid', // 必填,公眾號的唯一標識
            //下面大括號內為視圖渲染
            timestamp: '{$timestamp}', // 必填,生成簽名的時間戳
            nonceStr: '{$nonceStr}', // 必填,生成簽名的隨機串
            signature: '{$signature}',// 必填,簽名,見附錄1
            jsApiList: [
                'onMenuShareTimeline',
                'onMenuShareAppMessage'
            ] // 必填,需要使用的JS接口列表,所有JS接口列表見附錄2
        });
        wx.ready(function(){
            //分享到朋友圈
            wx.onMenuShareTimeline({
                title: '分享到朋友圈', // 分享標題
                link: 'https://www.baidu.com/', // 分享鏈接
                imgUrl: 'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png', // 分享圖標
                success: function () { 
                    // 用戶確認分享后執(zhí)行的回調函數(shù)
                },
                cancel: function () { 
                    // 用戶取消分享后執(zhí)行的回調函數(shù)
                }
            });

            //分享給朋友
            wx.onMenuShareAppMessage({
                title: '分享給朋友', // 分享標題
                desc: '開發(fā) 分享給朋友功能', // 分享描述
                link: 'https://www.baidu.com/', // 分享鏈接
                imgUrl: 'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png', // 分享圖標
                type: 'link', // 分享類型,music、video或link,不填默認為link
                dataUrl: '', // 如果type是music或video,則要提供數(shù)據(jù)鏈接,默認為空
                success: function () { 
                    // 用戶確認分享后執(zhí)行的回調函數(shù)
                },
                cancel: function () { 
                    // 用戶取消分享后執(zhí)行的回調函數(shù)
                }
            });
        });
        wx.error(function(res){});
    </script>
</body>
</html>

控制器的index方法:

public function index(){
    // 獲取jsapi_ticket票據(jù)
    $jsapi_ticket = getJsApiTicket();
    // 生成signature
    $nonceStr = randomString();
    $url = '調用JS接口頁面的完整URL';
    $signature = "jsapi_ticket=".$jsapi_ticket."&noncestr=".$nonceStr."&timestamp=".$timestamp."&url=".$url;
    $signature = sha1($signature);
    $this->assign('timestamp',$timestamp);
    $this->assign('nonceStr',$nonceStr);
    $this->assign('signature',$signature);
    $this->display("index");
    
    // 獲取jsapi_ticket,它是公眾號用于調用微信JS接口的臨時票據(jù)
    function getJsApiTicket(){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=公眾號的appid&secret=公眾號的secret";
        $res = (array)json_decode(httpRequest($url,'get'));
        $access_token = $res['access_token'];
        $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$access_token.'&type=jsapi';
        $res = (array)json_decode(httpRequest($url,'get'));
        $jsapi_ticket = $res['ticket'];
        return $jsapi_ticket;
    }

    //生成指定長度的隨機串
    function randomString(){
        srand(microtime()*10000000);
        $possible="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        $str="";
        $len = 16;
        while(strlen($str)<$len) {
            $str.=substr($possible,(rand()%(strlen($possible))),1);
        }
        return $str;
    }

    //使用curl進行請求,$method='get'or'post'
    function httpRequest($url, $method='get', $data='undefined'){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        if ($method == 'get'){
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22");
            curl_setopt($ch, CURLOPT_ENCODING ,'gzip'); //加入gzip解析
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);    // https請求 不驗證證書和hosts
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }           
        if ($method == 'post'){
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            if (curl_errno($ch)) {
                return curl_error($ch);
            }
        }   
        $output = curl_exec($ch);       
        curl_close($ch);
        return $output;
    }
}

參考教程:
PHP微信公眾平臺開發(fā)高級篇—微信JS-SDK
微信JS-SDK說明文檔

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容