微信js SDK接口

微信JS-SDK說明文檔 http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.htmljavascript

1、微信登陸功能css

       在進行微信OAuth2.在進行微信OAuth2.0受權登陸接入以前,在微信開放平臺註冊開發者賬號,並擁有一個已審覈經過的網站應用,並得到相應的AppID和AppSecret,申請微信登陸且經過審覈後,可開始接入流程。(微信開放平臺網址:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CNhtml

實例效果:java

<!DOCTYPE html>
<html>
<head>
    <title>微信登陸功能</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="description" content="">
    <meta name="keywords" content="">
    <script src="http://www.xueersi.com/lib/jQuery/1.11.1/jquery.min.js?1458897912"></script>
</head>
<body>
 <a href="https://open.weixin.qq.com/connect/qrconnect?appid=wx6b26b7c75e8f3e5a&redirect_uri=http%3A%2F%2Fwww.imooc.com%2Fpassport%2Fuser%2Ftpcallback%3Freferer%3Dhttp%3A%2F%2Fwww.imooc.com%26tp%3Dweixin%26bind%3D0&response_type=code&scope=snsapi_login#wechat_redirect">慕課網微信登陸功能</a>
 <a href="https://open.weixin.qq.com/connect/qrconnect?appid=wxadfc3188c82ef252&redirect_uri=http%3A%2F%2Fpassport.jikexueyuan.com%2Fconnect%2Fsuccess%3Ft%3Dweixin&response_type=code&scope=snsapi_login&t=weixin&state=weixin#wechat_redirect">極客學院微信登陸功能</a>
 <button id="LoginBtn">測試微信登陸功能</button>
 <div id="WXBox"></div>
</body>
</html>
<script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>

<script type="text/javascript">
//js微信登陸功能能夠直接將全部配置寫在a標籤的額href連接中也能夠寫在js配置中
 $('#LoginBtn').click(function(){
   var obj =   new WxLogin({
      id:"WXBox", //第三方頁面顯示二維碼的容器id
      appid: "wxadfc3188c82ef252", //應用惟一標識,在微信開放平臺提交應用審覈經過後得到
      scope: "snsapi_login", //應用受權做用域,擁有多個做用域用逗號(,)分隔,網頁應用目前僅填寫snsapi_login便可
      redirect_uri: "http%3A%2F%2Fpassport.jikexueyuan.com%2Fconnect%2Fsuccess%3Ft%3Dweixin",//重定向地址,須要進行UrlEncode
      state: "weixin#wechat_redirect"//用於保持請求和回調的狀態,受權請求後原樣帶回給第三方。該參數可用於防止csrf攻擊(跨站請求僞造攻擊),建議第三方帶上該參數,可設置爲簡單的隨機數加session進行校驗
    });
 })
</script>

jquery

2、微信JS接口相關功能實例git

微信JS接口 分享到朋友圈 分享給朋友 分享到QQ 拍照或從手機相冊中選圖 識別音頻並返回識別結果 使用微信內置地圖查看位置
來源:http://www.cnblogs.com/txw1958/p/weixin-js.html web


概述

微信JS-SDK是微信公衆平臺面向網頁開發者提供的基於微信內的網頁開發工具包。 chrome

經過使用微信JS-SDK,網頁開發者可藉助微信高效地使用拍照、選圖、語音、位置等手機系統的能力,同時能夠直接使用微信分享、掃一掃、卡券、支付等微信特有的能力,爲微信用戶提供更優質的網頁體驗。 api

此文檔面向網頁開發者介紹微信JS-SDK如何使用及相關注意事項。 安全


使用說明

在使用微信JS-SDK對應的JS接口前,需確保公衆號已得到使用對應JS接口的權限,可登陸微信公衆平臺進入「開發者中心」查看對應的接口權限。

注意: 全部的JS接口只能在公衆號綁定的域名下調用,公衆號開發者須要先登陸微信公衆平臺進入「公衆號設置」》「功能設置」裏填寫「JS接口安全域名」。

步驟一:引入JS文件

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

備註:支持使用 AMD/CMD 標準模塊加載方法加載

步驟二:經過config接口注入權限驗證配置

全部須要使用JS-SDK的頁面必須先注入配置信息,不然將沒法調用(同一個url僅需調用一次,對於變化url的SPA的web app可在每次url變化時進行調用)。

wx.config({
    debug: true, // 開啓調試模式,調用的全部api的返回值會在客戶端alert出來,若要查看傳入的參數,能夠在pc端打開,參數信息會經過log打出,僅在pc端時纔會打印。
    appId: '', // 必填,公衆號的惟一標識
    timestamp: , // 必填,生成簽名的時間戳
    nonceStr: '', // 必填,生成簽名的隨機串
    signature: '',// 必填,簽名,見附錄1
    jsApiList: [] // 必填,須要使用的JS接口列表,全部JS接口列表見附錄2
});


步驟三:經過ready接口處理成功驗證

wx.ready(function(){

    // config信息驗證後會執行ready方法,全部接口調用都必須在config接口得到結果以後,config是一個客戶端的異步操做,因此若是須要在頁面加載時就調用相關接口,則須把相關接口放在ready函數中調用來確保正確執行。對於用戶觸發時才調用的接口,則能夠直接調用,不須要放在ready函數中。
});


步驟四:經過error接口處理失敗驗證

wx.error(function(res){

    // config信息驗證失敗會執行error函數,如簽名過時致使驗證失敗,具體錯誤信息能夠打開config的debug模式查看,也能夠在返回的res參數中查看,對於SPA能夠在這裏更新簽名。

});

接口調用說明

全部接口經過wx對象(也可以使用jWeixin對象)來調用,參數是一個對象,除了每一個接口自己須要傳的參數以外,還有如下通用參數:

  1. success:接口調用成功時執行的回調函數。
  2. fail:接口調用失敗時執行的回調函數。
  3. complete:接口調用完成時執行的回調函數,不管成功或失敗都會執行。
  4. cancel:用戶點擊取消時的回調函數,僅部分有用戶取消操做的api纔會用到。
  5. trigger: 監聽Menu中的按鈕點擊時觸發的方法,該方法僅支持Menu中的相關接口。


以上幾個函數都帶有一個參數,類型爲對象,其中除了每一個接口自己返回的數據以外,還有一個通用屬性errMsg,其值格式以下:

  1. 調用成功時:"xxx:ok" ,其中xxx爲調用的接口名
  2. 用戶取消時:"xxx:cancel",其中xxx爲調用的接口名
  3. 調用失敗時:其值爲具體錯誤信息

基礎接口

判斷當前客戶端版本是否支持指定JS接口

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

備註:checkJsApi接口是客戶端6.0.2新引入的一個預留接口,第一期開放的接口都可不使用checkJsApi來檢測。

分享接口

請注意不要有誘導分享等違規行爲,對於誘導分享行爲將永久回收公衆號接口權限,詳細規則請查看:朋友圈管理常見問題

獲取「分享到朋友圈」按鈕點擊狀態及自定義分享內容接口

wx.onMenuShareTimeline({
    title: '', // 分享標題
    link: '', // 分享連接
    imgUrl: '', // 分享圖標
    success: function () { 
        // 用戶確認分享後執行的回調函數
    },
    cancel: function () { 
        // 用戶取消分享後執行的回調函數
    }
});

獲取「分享給朋友」按鈕點擊狀態及自定義分享內容接口

wx.onMenuShareAppMessage({
    title: '', // 分享標題
    desc: '', // 分享描述
    link: '', // 分享連接
    imgUrl: '', // 分享圖標
    type: '', // 分享類型,music、video或link,不填默認爲link
    dataUrl: '', // 若是type是music或video,則要提供數據連接,默認爲空
    success: function () { 
        // 用戶確認分享後執行的回調函數
    },
    cancel: function () { 
        // 用戶取消分享後執行的回調函數
    }
});

獲取「分享到QQ」按鈕點擊狀態及自定義分享內容接口

wx.onMenuShareQQ({
    title: '', // 分享標題
    desc: '', // 分享描述
    link: '', // 分享連接
    imgUrl: '' // 分享圖標
    success: function () { 
       // 用戶確認分享後執行的回調函數
    },
    cancel: function () { 
       // 用戶取消分享後執行的回調函數
    }
});

獲取「分享到騰訊微博」按鈕點擊狀態及自定義分享內容接口

wx.onMenuShareWeibo({
    title: '', // 分享標題
    desc: '', // 分享描述
    link: '', // 分享連接
    imgUrl: '' // 分享圖標
    success: function () { 
       // 用戶確認分享後執行的回調函數
    },
    cancel: function () { 
        // 用戶取消分享後執行的回調函數
    }
});

圖像接口

拍照或從手機相冊中選圖接口

wx.chooseImage({
    success: function (res) {
        var localIds = res.localIds; // 返回選定照片的本地ID列表,localId能夠做爲img標籤的src屬性顯示圖片
    }
});

預覽圖片接口

wx.previewImage({
    current: '', // 當前顯示的圖片連接
    urls: [] // 須要預覽的圖片連接列表
});

上傳圖片接口

wx.uploadImage({
    localId: '', // 須要上傳的圖片的本地ID,由chooseImage接口得到
    isShowProgressTips: 1// 默認爲1,顯示進度提示
    success: function (res) {
        var serverId = res.serverId; // 返回圖片的服務器端ID
    }
});

備註:可用微信下載多媒體文件接口下載上傳的圖片,此處得到的 serverId 即 media_id,參考文檔 ../12/58bfcfabbd501c7cd77c19bd9cfa8354.html


下載圖片接口

wx.downloadImage({
    serverId: '', // 須要下載的圖片的服務器端ID,由uploadImage接口得到
    isShowProgressTips: 1// 默認爲1,顯示進度提示
    success: function (res) {
        var localId = res.localId; // 返回圖片下載後的本地ID
    }
});

音頻接口

開始錄音接口

wx.startRecord();

中止錄音接口

wx.stopRecord({
    success: function (res) {
        var localId = res.localId;
    }
});

監聽錄音自動中止接口

wx.onVoiceRecordEnd({
    // 錄音時間超過一分鐘沒有中止的時候會執行 complete 回調
    complete: function (res) {
        var localId = res.localId; 
    }
});

播放語音接口

wx.playVoice({
    localId: '' // 須要播放的音頻的本地ID,由stopRecord接口得到
});


暫停播放接口

wx.pauseVoice({
    localId: '' // 須要暫停的音頻的本地ID,由stopRecord接口得到
});

中止播放接口

wx.stopVoice({
    localId: '' // 須要中止的音頻的本地ID,由stopRecord接口得到
});

監聽語音播放完畢接口

wx.onVoicePlayEnd({
    serverId: '', // 須要下載的音頻的服務器端ID,由uploadVoice接口得到
    success: function (res) {
        var localId = res.localId; // 返回音頻的本地ID
    }
});


上傳語音接口

wx.uploadVoice({
    localId: '', // 須要上傳的音頻的本地ID,由stopRecord接口得到
    isShowProgressTips: 1// 默認爲1,顯示進度提示
        success: function (res) {
        var serverId = res.serverId; // 返回音頻的服務器端ID
    }
});

備註:可用微信下載多媒體文件接口下載上傳的語音,此處得到的 serverId 即 media_id,參考文檔 ../12/58bfcfabbd501c7cd77c19bd9cfa8354.html


下載語音接口

wx.downloadVoice({
    serverId: '', // 須要下載的音頻的服務器端ID,由uploadVoice接口得到
    isShowProgressTips: 1// 默認爲1,顯示進度提示
    success: function (res) {
        var localId = res.localId; // 返回音頻的本地ID
    }
});


智能接口

識別音頻並返回識別結果接口

wx.translateVoice({
   localId: '', // 須要識別的音頻的本地Id,由錄音相關接口得到
    isShowProgressTips: 1, // 默認爲1,顯示進度提示
    success: function (res) {
        alert(res.translateResult); // 語音識別的結果
    }
});

設備信息

獲取網絡狀態接口

wx.getNetworkType({
    success: function (res) {
        var networkType = res.networkType; // 返回網絡類型2g,3g,4g,wifi
    }
});


地理位置

使用微信內置地圖查看位置接口

wx.openLocation({
    latitude: 0, // 緯度,浮點數,範圍爲90 ~ -90
    longitude: 0, // 經度,浮點數,範圍爲180 ~ -180。
    name: '', // 位置名
    address: '', // 地址詳情說明
    scale: 1, // 地圖縮放級別,整形值,範圍從1~28。默認爲最大
    infoUrl: '' // 在查看位置界面底部顯示的超連接,可點擊跳轉
});

獲取地理位置接口

wx.getLocation({
    timestamp: 0, // 位置簽名時間戳,僅當須要兼容6.0.2版本以前時提供
    nonceStr: '', // 位置簽名隨機串,僅當須要兼容6.0.2版本以前時提供
    addrSign: '', // 位置簽名,僅當須要兼容6.0.2版本以前時提供,詳見附錄4
    success: function (res) {
       var longitude = res.longitude; // 緯度,浮點數,範圍爲90 ~ -90
       var latitude = res.latitude; // 經度,浮點數,範圍爲180 ~ -180。
        var speed = res.speed; // 速度,以米/每秒計
        var accuracy = res.accuracy; // 位置精度
    }
});


界面操做

隱藏右上角菜單接口

wx.hideOptionMenu();

顯示右上角菜單接口

wx.showOptionMenu();

關閉當前網頁窗口接口

wx.closeWindow();

批量隱藏功能按鈕接口

wx.hideMenuItems({
    menuList: [] // 要隱藏的菜單項,全部menu項見附錄3
});

批量顯示功能按鈕接口

wx.showMenuItems({
    menuList: [] // 要顯示的菜單項,全部menu項見附錄3
});

隱藏全部非基礎按鈕接口

wx.hideAllNonBaseMenuItem();

顯示全部功能按鈕接口

wx.showAllNonBaseMenuItem();

微信掃一掃

調起微信掃一掃接口

wx.scanQRCode({
    desc: 'scanQRCode desc',
    needResult: 0, // 默認爲0,掃描結果由微信處理,1則直接返回掃描結果,
    scanType: ["qrCode","barCode"], // 能夠指定掃二維碼仍是一維碼,默認兩者都有
    success: function (res) {
    var result = res.resultStr; // 當needResult 爲 1 時,掃碼返回的結果
}
});

微信小店

跳轉微信商品頁接口

wx.openProductSpecificView({
    productId: '', // 商品id
    viewType: '' // 0.默認值,普通商品詳情頁1.掃一掃商品詳情頁2.小店商品詳情頁
});


微信卡券

調起適用於門店的卡券列表並獲取用戶選擇列表

wx.chooseCard({
    shopId: '', // 門店Id
    cardType: '', // 卡券類型
    cardId: '', // 卡券Id
    timeStamp: 0, // 卡券簽名時間戳
    nonceStr: '', // 卡券簽名隨機串
    cardSign: '', // 卡券簽名,詳見附錄6
    success: function (res) {
        var cardList= res.cardList; // 用戶選中的卡券列表信息
    }
});

批量添加卡券接口

wx.addCard({
    cardList: [{
        cardId: '',
        cardExt: ''
    }], // 須要添加的卡券列表
    success: function (res) {
        var cardList = res.cardList; // 添加的卡券列表信息
    }
});

查看微信卡包中的卡券接口

wx.openCard({
    cardList: [{
        cardId: '',
        code: ''
    }]// 須要打開的卡券列表
});


微信支付

發起一個微信支付請求

wx.chooseWXPay({
    timestamp: 0, // 支付簽名時間戳
    noncestr: '', // 支付簽名隨機串
    package: '', // 訂單詳情擴展字符串,詳見附錄5
    paySign: '', // 支付簽名,詳見附錄5
});


html代碼部分:

<!DOCTYPE html>    
<html>    
<head>    
<meta charset="utf-8">    
<title>微信JS-SDK Demo</title>    
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">    
<link rel="stylesheet" href="css/style.css">    
</head>    
<body ontouchstart="">    
<div class="wxapi_container">    
<div class="wxapi_index_container">    
<ul class="label_box lbox_close wxapi_index_list">    
<li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-basic">基礎接口</a></li>    
<li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-share">分享接口</a></li>    
<li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-image">圖像接口</a></li>    
<li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-voice">音頻接口</a></li>    
<li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-smart">智能接口</a></li>    
<li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-device">設備信息接口</a></li>    
<li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-location">地理位置接口</a></li>    
<li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-webview">界面操做接口</a></li>    
<li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-scan">微信掃一掃接口</a></li>    
<li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-shopping">微信小店接口</a></li>    
<li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-card">微信卡券接口</a></li>    
<li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-pay">微信支付接口</a></li>    
</ul>    
</div>    
<div class="lbox_close wxapi_form">    
<h3 id="menu-basic">基礎接口</h3>    
<span class="desc">判斷當前客戶端是否支持指定JS接口</span>    
<button class="btn btn_primary" id="checkJsApi">checkJsApi</button>    
<h3 id="menu-share">分享接口</h3>    
<span class="desc">獲取「分享到朋友圈」按鈕點擊狀態及自定義分享內容接口</span>    
<button class="btn btn_primary" id="onMenuShareTimeline">onMenuShareTimeline</button>    
<span class="desc">獲取「分享給朋友」按鈕點擊狀態及自定義分享內容接口</span>    
<button class="btn btn_primary" id="onMenuShareAppMessage">onMenuShareAppMessage</button>    
<span class="desc">獲取「分享到QQ」按鈕點擊狀態及自定義分享內容接口</span>    
<button class="btn btn_primary" id="onMenuShareQQ">onMenuShareQQ</button>    
<span class="desc">獲取「分享到騰訊微博」按鈕點擊狀態及自定義分享內容接口</span>    
<button class="btn btn_primary" id="onMenuShareWeibo">onMenuShareWeibo</button>    
<h3 id="menu-image">圖像接口</h3>    
<span class="desc">拍照或從手機相冊中選圖接口</span>    
<button class="btn btn_primary" id="chooseImage">chooseImage</button>    
<span class="desc">預覽圖片接口</span>    
<button class="btn btn_primary" id="previewImage">previewImage</button>    
<span class="desc">上傳圖片接口</span>    
<button class="btn btn_primary" id="uploadImage">uploadImage</button>    
<span class="desc">下載圖片接口</span>    
<button class="btn btn_primary" id="downloadImage">downloadImage</button>    
<h3 id="menu-voice">音頻接口</h3>    
<span class="desc">開始錄音接口</span>    
<button class="btn btn_primary" id="startRecord">startRecord</button>    
<span class="desc">中止錄音接口</span>    
<button class="btn btn_primary" id="stopRecord">stopRecord</button>    
<span class="desc">播放語音接口</span>    
<button class="btn btn_primary" id="playVoice">playVoice</button>    
<span class="desc">暫停播放接口</span>    
<button class="btn btn_primary" id="pauseVoice">pauseVoice</button>    
<span class="desc">中止播放接口</span>    
<button class="btn btn_primary" id="stopVoice">stopVoice</button>    
<span class="desc">上傳語音接口</span>    
<button class="btn btn_primary" id="uploadVoice">uploadVoice</button>    
<span class="desc">下載語音接口</span>    
<button class="btn btn_primary" id="downloadVoice">downloadVoice</button>    
<h3 id="menu-smart">智能接口</h3>    
<span class="desc">識別音頻並返回識別結果接口</span>    
<button class="btn btn_primary" id="translateVoice">translateVoice</button>    
<h3 id="menu-device">設備信息接口</h3>    
<span class="desc">獲取網絡狀態接口</span>    
<button class="btn btn_primary" id="getNetworkType">getNetworkType</button>    
<h3 id="menu-location">地理位置接口</h3>    
<span class="desc">使用微信內置地圖查看位置接口</span>    
<button class="btn btn_primary" id="openLocation">openLocation</button>    
<span class="desc">獲取地理位置接口</span>    
<button class="btn btn_primary" id="getLocation">getLocation</button>    
<h3 id="menu-webview">界面操做接口</h3>    
<span class="desc">隱藏右上角菜單接口</span>    
<button class="btn btn_primary" id="hideOptionMenu">hideOptionMenu</button>    
<span class="desc">顯示右上角菜單接口</span>    
<button class="btn btn_primary" id="showOptionMenu">showOptionMenu</button>    
<span class="desc">關閉當前網頁窗口接口</span>    
<button class="btn btn_primary" id="closeWindow">closeWindow</button>    
<span class="desc">批量隱藏功能按鈕接口</span>    
<button class="btn btn_primary" id="hideMenuItems">hideMenuItems</button>    
<span class="desc">批量顯示功能按鈕接口</span>    
<button class="btn btn_primary" id="showMenuItems">showMenuItems</button>    
<span class="desc">隱藏全部非基礎按鈕接口</span>    
<button class="btn btn_primary" id="hideAllNonBaseMenuItem">hideAllNonBaseMenuItem</button>    
<span class="desc">顯示全部功能按鈕接口</span>    
<button class="btn btn_primary" id="showAllNonBaseMenuItem">showAllNonBaseMenuItem</button>    
<h3 id="menu-scan">微信掃一掃</h3>    
<span class="desc">調起微信掃一掃接口</span>    
<button class="btn btn_primary" id="scanQRCode0">scanQRCode(微信處理結果)</button>    
<button class="btn btn_primary" id="scanQRCode1">scanQRCode(直接返回結果)</button>    
<h3 id="menu-shopping">微信小店接口</h3>    
<span class="desc">跳轉微信商品頁接口</span>    
<button class="btn btn_primary" id="openProductSpecificView">openProductSpecificView</button>    
<h3 id="menu-card">微信卡券接口</h3>    
<span class="desc">批量添加卡券接口</span>    
<button class="btn btn_primary" id="addCard">addCard</button>    
<span class="desc">調起適用於門店的卡券列表並獲取用戶選擇列表</span>    
<button class="btn btn_primary" id="chooseCard">chooseCard</button>    
<span class="desc">查看微信卡包中的卡券接口</span>    
<button class="btn btn_primary" id="openCard">openCard</button>    
<h3 id="menu-pay">微信支付接口</h3>    
<span class="desc">發起一個微信支付請求</span>    
<button class="btn btn_primary" id="chooseWXPay">chooseWXPay</button>    
</div>    
</div>    
</body>    
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>    
<script>    
/*    
* 注意:    
* 1. 全部的JS接口只能在公衆號綁定的域名下調用,公衆號開發者須要先登陸微信公衆平臺進入「公衆號設置」的「功能設置」裏填寫「JS接口安全域名」。    
* 2. 若是發如今 Android 不能分享自定義內容,請到官網下載最新的包覆蓋安裝,Android 自定義分享接口需升級至 6.0.2.58 版本及以上。    
* 3. 完整 JS-SDK 文檔地址:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html    
*    
* 若有問題請經過如下渠道反饋:    
* 郵箱地址:weixin-open@qq.com    
* 郵件主題:【微信JS-SDK反饋】具體問題    
* 郵件內容說明:用簡明的語言描述問題所在,並交代清楚遇到該問題的場景,可附上截屏圖片,微信團隊會盡快處理你的反饋。    
*/    
wx.config({    
debug: false,    
appId: 'wxf8b4f85f3a794e77',    
timestamp: 1421142450,    
nonceStr: '9hKgyCLgGZOgQmEI',    
signature: 'bf7a5555f9ad0e7e491535f232349a40510a6f8f',    
jsApiList: [    
'checkJsApi',    
'onMenuShareTimeline',    
'onMenuShareAppMessage',    
'onMenuShareQQ',    
'onMenuShareWeibo',    
'hideMenuItems',    
'showMenuItems',    
'hideAllNonBaseMenuItem',    
'showAllNonBaseMenuItem',    
'translateVoice',    
'startRecord',    
'stopRecord',    
'onRecordEnd',    
'playVoice',    
'pauseVoice',    
'stopVoice',    
'uploadVoice',    
'downloadVoice',    
'chooseImage',    
'previewImage',    
'uploadImage',    
'downloadImage',    
'getNetworkType',    
'openLocation',    
'getLocation',    
'hideOptionMenu',    
'showOptionMenu',    
'closeWindow',    
'scanQRCode',    
'chooseWXPay',    
'openProductSpecificView',    
'addCard',    
'chooseCard',    
'openCard'    
]    
});    
</script>    
<script src="js/demo.js"> </script>    
</html>demo.js部分:

/*
   * 注意:
   * 1. 全部的JS接口只能在公衆號綁定的域名下調用,公衆號開發者須要先登陸微信公衆平臺進入「公衆號設置」的「功能設置」裏填寫「JS接口安全域名」。
   * 2. 若是發如今 Android 不能分享自定義內容,請到官網下載最新的包覆蓋安裝,Android 自定義分享接口需升級至 6.0.2.58 版本及以上。
   * 3. 完整 JS-SDK 文檔地址:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
   *
   * 若有問題請經過如下渠道反饋:
   * 郵箱地址:weixin-open@qq.com
   * 郵件主題:【微信JS-SDK反饋】具體問題
   * 郵件內容說明:用簡明的語言描述問題所在,並交代清楚遇到該問題的場景,可附上截屏圖片,微信團隊會盡快處理你的反饋。
   */
  wx.config({
      debug: false,
      appId: 'wxf8b4f85f3a794e77',
      timestamp: 1421142450,
      nonceStr: '9hKgyCLgGZOgQmEI',
      signature: 'bf7a5555f9ad0e7e491535f232349a40510a6f8f',
      jsApiList: [
        'checkJsApi',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo',
        'hideMenuItems',
        'showMenuItems',
        'hideAllNonBaseMenuItem',
        'showAllNonBaseMenuItem',
        'translateVoice',
        'startRecord',
        'stopRecord',
        'onRecordEnd',
        'playVoice',
        'pauseVoice',
        'stopVoice',
        'uploadVoice',
        'downloadVoice',
        'chooseImage',
        'previewImage',
        'uploadImage',
        'downloadImage',
        'getNetworkType',
        'openLocation',
        'getLocation',
        'hideOptionMenu',
        'showOptionMenu',
        'closeWindow',
        'scanQRCode',
        'chooseWXPay',
        'openProductSpecificView',
        'addCard',
        'chooseCard',
        'openCard'
      ]
  });
/*
 * 注意:
 * 1. 全部的JS接口只能在公衆號綁定的域名下調用,公衆號開發者須要先登陸微信公衆平臺進入「公衆號設置」的「功能設置」裏填寫「JS接口安全域名」。
 * 2. 若是發如今 Android 不能分享自定義內容,請到官網下載最新的包覆蓋安裝,Android 自定義分享接口需升級至 6.0.2.58 版本及以上。
 * 3. 完整 JS-SDK 文檔地址:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
 *
 * 若有問題請經過如下渠道反饋:
 * 郵箱地址:weixin-open@qq.com
 * 郵件主題:【微信JS-SDK反饋】具體問題
 * 郵件內容說明:用簡明的語言描述問題所在,並交代清楚遇到該問題的場景,可附上截屏圖片,微信團隊會盡快處理你的反饋。
 */
wx.ready(function () {
  // 1 判斷當前版本是否支持指定 JS 接口,支持批量判斷
  document.querySelector('#checkJsApi').onclick = function () {
    wx.checkJsApi({
      jsApiList: [
        'getNetworkType',
        'previewImage'
      ],
      success: function (res) {
        alert(JSON.stringify(res));
      }
    });
  };
  // 2. 分享接口
  // 2.1 監聽「分享給朋友」,按鈕點擊、自定義分享內容及分享結果接口
  document.querySelector('#onMenuShareAppMessage').onclick = function () {
    wx.onMenuShareAppMessage({
      title: '互聯網之子',
      desc: '在長大的過程當中,我才慢慢發現,我身邊的全部事,別人跟我說的全部事,那些所謂原本如此,註定如此的事,它們其實沒有非得如此,事情是能夠改變的。更重要的是,有些事既然錯了,那就該作出改變。',
      link: 'http://movie.douban.com/subject/25785114/',
      imgUrl: 'http://img3.douban.com/view/movie_poster_cover/spst/public/p2166127561.jpg',
      trigger: function (res) {
        alert('用戶點擊發送給朋友');
      },
      success: function (res) {
        alert('已分享');
      },
      cancel: function (res) {
        alert('已取消');
      },
      fail: function (res) {
        alert(JSON.stringify(res));
      }
    });
    alert('已註冊獲取「發送給朋友」狀態事件');
  };
  // 2.2 監聽「分享到朋友圈」按鈕點擊、自定義分享內容及分享結果接口
  document.querySelector('#onMenuShareTimeline').onclick = function () {
    wx.onMenuShareTimeline({
      title: '互聯網之子',
      link: 'http://movie.douban.com/subject/25785114/',
      imgUrl: 'http://img3.douban.com/view/movie_poster_cover/spst/public/p2166127561.jpg',
      trigger: function (res) {
        alert('用戶點擊分享到朋友圈');
      },
      success: function (res) {
        alert('已分享');
      },
      cancel: function (res) {
        alert('已取消');
      },
      fail: function (res) {
        alert(JSON.stringify(res));
      }
    });
    alert('已註冊獲取「分享到朋友圈」狀態事件');
  };
  // 2.3 監聽「分享到QQ」按鈕點擊、自定義分享內容及分享結果接口
  document.querySelector('#onMenuShareQQ').onclick = function () {
    wx.onMenuShareQQ({
      title: '互聯網之子',
      desc: '在長大的過程當中,我才慢慢發現,我身邊的全部事,別人跟我說的全部事,那些所謂原本如此,註定如此的事,它們其實沒有非得如此,事情是能夠改變的。更重要的是,有些事既然錯了,那就該作出改變。',
      link: 'http://movie.douban.com/subject/25785114/',
      imgUrl: 'http://img3.douban.com/view/movie_poster_cover/spst/public/p2166127561.jpg',
      trigger: function (res) {
        alert('用戶點擊分享到QQ');
      },
      complete: function (res) {
        alert(JSON.stringify(res));
      },
      success: function (res) {
        alert('已分享');
      },
      cancel: function (res) {
        alert('已取消');
      },
      fail: function (res) {
        alert(JSON.stringify(res));
      }
    });
    alert('已註冊獲取「分享到 QQ」狀態事件');
  };
 
  // 2.4 監聽「分享到微博」按鈕點擊、自定義分享內容及分享結果接口
  document.querySelector('#onMenuShareWeibo').onclick = function () {
    wx.onMenuShareWeibo({
      title: '互聯網之子',
      desc: '在長大的過程當中,我才慢慢發現,我身邊的全部事,別人跟我說的全部事,那些所謂原本如此,註定如此的事,它們其實沒有非得如此,事情是能夠改變的。更重要的是,有些事既然錯了,那就該作出改變。',
      link: 'http://movie.douban.com/subject/25785114/',
      imgUrl: 'http://img3.douban.com/view/movie_poster_cover/spst/public/p2166127561.jpg',
      trigger: function (res) {
        alert('用戶點擊分享到微博');
      },
      complete: function (res) {
        alert(JSON.stringify(res));
      },
      success: function (res) {
        alert('已分享');
      },
      cancel: function (res) {
        alert('已取消');
      },
      fail: function (res) {
        alert(JSON.stringify(res));
      }
    });
    alert('已註冊獲取「分享到微博」狀態事件');
  };

  // 3 智能接口
  var voice = {
    localId: '',
    serverId: ''
  };
  // 3.1 識別音頻並返回識別結果
  document.querySelector('#translateVoice').onclick = function () {
    if (voice.localId == '') {
      alert('請先使用 startRecord 接口錄製一段聲音');
      return;
    }
    wx.translateVoice({
      localId: voice.localId,
      complete: function (res) {
        if (res.hasOwnProperty('translateResult')) {
          alert('識別結果:' + res.translateResult);
        } else {
          alert('沒法識別');
        }
      }
    });
  };
  // 4 音頻接口
  // 4.2 開始錄音
  document.querySelector('#startRecord').onclick = function () {
    wx.startRecord({
      cancel: function () {
        alert('用戶拒絕受權錄音');
      }
    });
  };
  // 4.3 中止錄音
  document.querySelector('#stopRecord').onclick = function () {
    wx.stopRecord({
      success: function (res) {
        voice.localId = res.localId;
      },
      fail: function (res) {
        alert(JSON.stringify(res));
      }
    });
  };
  // 4.4 監聽錄音自動中止
  wx.onVoiceRecordEnd({
    complete: function (res) {
      voice.localId = res.localId;
      alert('錄音時間已超過一分鐘');
    }
  });
  // 4.5 播放音頻
  document.querySelector('#playVoice').onclick = function () {
    if (voice.localId == '') {
      alert('請先使用 startRecord 接口錄製一段聲音');
      return;
    }
    wx.playVoice({
      localId: voice.localId
    });
  };
  // 4.6 暫停播放音頻
  document.querySelector('#pauseVoice').onclick = function () {
    wx.pauseVoice({
      localId: voice.localId
    });
  };
  // 4.7 中止播放音頻
  document.querySelector('#stopVoice').onclick = function () {
    wx.stopVoice({
      localId: voice.localId
    });
  };
  // 4.8 監聽錄音播放中止
  wx.onVoicePlayEnd({
    complete: function (res) {
      alert('錄音(' + res.localId + ')播放結束');
    }
  });
  // 4.8 上傳語音
  document.querySelector('#uploadVoice').onclick = function () {
    if (voice.localId == '') {
      alert('請先使用 startRecord 接口錄製一段聲音');
      return;
    }
    wx.uploadVoice({
      localId: voice.localId,
      success: function (res) {
        alert('上傳語音成功,serverId 爲' + res.serverId);
        voice.serverId = res.serverId;
      }
    });
  };
  // 4.9 下載語音
  document.querySelector('#downloadVoice').onclick = function () {
    if (voice.serverId == '') {
      alert('請先使用 uploadVoice 上傳聲音');
      return;
    }
    wx.downloadVoice({
      serverId: voice.serverId,
      success: function (res) {
        alert('下載語音成功,localId 爲' + res.localId);
        voice.localId = res.localId;
      }
    });
  };
  // 5 圖片接口
  // 5.1 拍照、本地選圖
  var images = {
    localId: [],
    serverId: []
  };
  document.querySelector('#chooseImage').onclick = function () {
    wx.chooseImage({
      success: function (res) {
        images.localId = res.localIds;
        alert('已選擇 ' + res.localIds.length + ' 張圖片');
      }
    });
  };
  // 5.2 圖片預覽
  document.querySelector('#previewImage').onclick = function () {
    wx.previewImage({
      current: 'http://img5.douban.com/view/photo/photo/public/p1353993776.jpg',
      urls: [
        'http://img3.douban.com/view/photo/photo/public/p2152117150.jpg',
        'http://img5.douban.com/view/photo/photo/public/p1353993776.jpg',
        'http://img3.douban.com/view/photo/photo/public/p2152134700.jpg'
      ]
    });
  };
  // 5.3 上傳圖片
  document.querySelector('#uploadImage').onclick = function () {
    if (images.localId.length == 0) {
      alert('請先使用 chooseImage 接口選擇圖片');
      return;
    }
    var i = 0, length = images.localId.length;
    images.serverId = [];
    function upload() {
      wx.uploadImage({
        localId: images.localId[i],
        success: function (res) {
          i++;
          alert('已上傳:' + i + '/' + length);
          images.serverId.push(res.serverId);
          if (i < length) {
            upload();
          }
        },
        fail: function (res) {
          alert(JSON.stringify(res));
        }
      });
    }
    upload();
  };
  // 5.4 下載圖片
  document.querySelector('#downloadImage').onclick = function () {
    if (images.serverId.length === 0) {
      alert('請先使用 uploadImage 上傳圖片');
      return;
    }
    var i = 0, length = images.serverId.length;
    images.localId = [];
    function download() {
      wx.downloadImage({
        serverId: images.serverId[i],
        success: function (res) {
          i++;
          alert('已下載:' + i + '/' + length);
          images.localId.push(res.localId);
          if (i < length) {
            download();
          }
        }
      });
    }
    download();
  };
  // 6 設備信息接口
  // 6.1 獲取當前網絡狀態
  document.querySelector('#getNetworkType').onclick = function () {
    wx.getNetworkType({
      success: function (res) {
        alert(res.networkType);
      },
      fail: function (res) {
        alert(JSON.stringify(res));
      }
    });
  };
  // 7 地理位置接口
  // 7.1 查看地理位置
  document.querySelector('#openLocation').onclick = function () {
    wx.openLocation({
      latitude: 23.099994,
      longitude: 113.324520,
      name: 'TIT 創意園',
      address: '廣州市海珠區新港中路 397 號',
      scale: 14,
      infoUrl: 'http://weixin.qq.com'
    });
  };
  // 7.2 獲取當前地理位置
  document.querySelector('#getLocation').onclick = function () {
    wx.getLocation({
      success: function (res) {
        alert(JSON.stringify(res));
      },
      cancel: function (res) {
        alert('用戶拒絕受權獲取地理位置');
      }
    });
  };
  // 8 界面操做接口
  // 8.1 隱藏右上角菜單
  document.querySelector('#hideOptionMenu').onclick = function () {
    wx.hideOptionMenu();
  };
  // 8.2 顯示右上角菜單
  document.querySelector('#showOptionMenu').onclick = function () {
    wx.showOptionMenu();
  };
  // 8.3 批量隱藏菜單項
  document.querySelector('#hideMenuItems').onclick = function () {
    wx.hideMenuItems({
      menuList: [
        'menuItem:readMode', // 閱讀模式
        'menuItem:share:timeline', // 分享到朋友圈
        'menuItem:copyUrl' // 複製連接
      ],
      success: function (res) {
        alert('已隱藏「閱讀模式」,「分享到朋友圈」,「複製連接」等按鈕');
      },
      fail: function (res) {
        alert(JSON.stringify(res));
      }
    });
  };
  // 8.4 批量顯示菜單項
  document.querySelector('#showMenuItems').onclick = function () {
    wx.showMenuItems({
      menuList: [
        'menuItem:readMode', // 閱讀模式
        'menuItem:share:timeline', // 分享到朋友圈
        'menuItem:copyUrl' // 複製連接
      ],
      success: function (res) {
        alert('已顯示「閱讀模式」,「分享到朋友圈」,「複製連接」等按鈕');
      },
      fail: function (res) {
        alert(JSON.stringify(res));
      }
    });
  };
  // 8.5 隱藏全部非基本菜單項
  document.querySelector('#hideAllNonBaseMenuItem').onclick = function () {
    wx.hideAllNonBaseMenuItem({
      success: function () {
        alert('已隱藏全部非基本菜單項');
      }
    });
  };
  // 8.6 顯示全部被隱藏的非基本菜單項
  document.querySelector('#showAllNonBaseMenuItem').onclick = function () {
    wx.showAllNonBaseMenuItem({
      success: function () {
        alert('已顯示全部非基本菜單項');
      }
    });
  };
  // 8.7 關閉當前窗口
  document.querySelector('#closeWindow').onclick = function () {
    wx.closeWindow();
  };
  // 9 微信原生接口
  // 9.1.1 掃描二維碼並返回結果
  document.querySelector('#scanQRCode0').onclick = function () {
    wx.scanQRCode({
      desc: 'scanQRCode desc'
    });
  };
  // 9.1.2 掃描二維碼並返回結果
  document.querySelector('#scanQRCode1').onclick = function () {
    wx.scanQRCode({
      needResult: 1,
      desc: 'scanQRCode desc',
      success: function (res) {
        alert(JSON.stringify(res));
      }
    });
  };
  // 10 微信支付接口
  // 10.1 發起一個支付請求
  document.querySelector('#chooseWXPay').onclick = function () {
    wx.chooseWXPay({
      timestamp: 1414723227,
      nonceStr: 'noncestr',
      package: 'addition=action_id%3dgaby1234%26limit_pay%3d&bank_type=WX&body=innertest&fee_type=1&input_charset=GBK&notify_url=http%3A%2F%2F120.204.206.246%2Fcgi-bin%2Fmmsupport-bin%2Fnotifypay&out_trade_no=1414723227818375338&partner=1900000109&spbill_create_ip=127.0.0.1&total_fee=1&sign=432B647FE95C7BF73BCD177CEECBEF8D',
      paySign: 'bd5b1933cda6e9548862944836a9b52e8c9a2b69'
    });
  };
  // 11.3  跳轉微信商品頁
  document.querySelector('#openProductSpecificView').onclick = function () {
    wx.openProductSpecificView({
      productId: 'pDF3iY_m2M7EQ5EKKKWd95kAxfNw'
    });
  };
  // 12 微信卡券接口
  // 12.1 添加卡券
  document.querySelector('#addCard').onclick = function () {
    wx.addCard({
      cardList: [
        {
          cardId: 'pDF3iY9tv9zCGCj4jTXFOo1DxHdo',
          cardExt: '{"code": "", "openid": "", "timestamp": "1418301401", "signature":"64e6a7cc85c6e84b726f2d1cbef1b36e9b0f9750"}'
        },
        {
          cardId: 'pDF3iY9tv9zCGCj4jTXFOo1DxHdo',
          cardExt: '{"code": "", "openid": "", "timestamp": "1418301401", "signature":"64e6a7cc85c6e84b726f2d1cbef1b36e9b0f9750"}'
        }
      ],
      success: function (res) {
        alert('已添加卡券:' + JSON.stringify(res.cardList));
      }
    });
  };
  // 12.2 選擇卡券
  document.querySelector('#chooseCard').onclick = function () {
    wx.chooseCard({
      cardSign: '97e9c5e58aab3bdf6fd6150e599d7e5806e5cb91',
      timestamp: 1417504553,
      nonceStr: 'k0hGdSXKZEj3Min5',
      success: function (res) {
        alert('已選擇卡券:' + JSON.stringify(res.cardList));
      }
    });
  };
  // 12.3 查看卡券
  document.querySelector('#openCard').onclick = function () {
    alert('您沒有該公衆號的卡券沒法打開卡券。');
    wx.openCard({
      cardList: [
      ]
    });
  };
  var shareData = {
    title: '微信JS-SDK Demo',
    desc: '微信JS-SDK,幫助第三方爲用戶提供更優質的移動web服務',
    link: 'http://demo.open.weixin.qq.com/jssdk/',
    imgUrl: 'http://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRt8Qia4lv7k3M9J1SKqKCImxJCt7j9rHYicKDI45jRPBxdzdyREWnk0ia0N5TMnMfth7SdxtzMvVgXg/0'
  };
  wx.onMenuShareAppMessage(shareData);
  wx.onMenuShareTimeline(shareData);
});
wx.error(function (res) {
  alert(res.errMsg);
});

html實例來源:http://my.oschina.net/superkangning/blog/367484實例來源http://my.oschina.net/superkangning/blog/367484http://my.oschina.net/superkangning/blog/367484
相關文章
相關標籤/搜索