微信開發各功能調用

前幾天使用微信做了個簽到系統,才發現作爲新開發也並不是像以前想的那麼難。同時也收集了一些常用的功能調用,今天和大家分享一下。

調用各個接口之前必須先進行微信配置:

 

//進入頁面  開始進行微信配置
$.ajax({
        type:"post",
        url:"",//請求地址
        data:{},
        success:function(result){
            var code = result.code,
                msg = result.msg;
            if(code!=0){
                $.toast(msg)
            }
            wx.config({
                // 開啓調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時纔會打印。
                debug: false,
                // 必填,公衆號的唯一標識
                appId: result.appId,
                // 必填,生成簽名的時間戳
                timestamp:""+result.timestamp,
                // 必填,生成簽名的隨機串
                nonceStr:result.noncestr,
                // 必填,簽名,見附錄1
                signature:result.signature,
                // 必填,需要使用的JS接口列表,所有JS接口列表見附錄2
                jsApiList : [ 'checkJsApi', 'scanQRCode' ]
            });
        }
    });
document.querySelector('#scanQRCode').onclick = function() {
    wx.scanQRCode({
        needResult : 1, // 默認爲0,掃描結果由微信處理,1則直接返回掃描結果,
        scanType : [ "qrCode"], // 可以指定掃二維碼還是一維碼,默認二者都有
        success : function(res) {
            var result = res.resultStr; // 當needResult 爲 1 時,掃碼返回的結果
            window.location.href = result;//掃描後有個鏈接,然後跳轉到該頁面
        }
    });
};
配置好之後我們就可以進行簡單的調用了。
/*
 * 注意:
 * 1. 所有的JS接口只能在公衆號綁定的域名下調用,公衆號開發者需要先登錄微信公衆平臺進入“公衆號設置”的“功能設置”裏填寫“JS接口安全域名”。
 * 2. 如果發現在 Android 不能分享自定義內容,請到官網下載最新的包覆蓋安裝,Android 自定義分享接口需升級至 6.0.2.58 版本及以上。
 * 3. 完整 JS-SDK 文檔地址:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
 *
 * 如有問題請通過以下渠道反饋:
 * 郵箱地址:[email protected]
 * 郵件主題:【微信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://demo.open.weixin.qq.com/jssdk/images/p2166127561.jpg',
            trigger: function (res) {
                // 不要嘗試在trigger中使用ajax異步請求修改本次分享的內容,因爲客戶端分享操作是一個同步操作,這時候使用ajax的回包會還沒有返回
                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://demo.open.weixin.qq.com/jssdk/images/p2166127561.jpg',
            trigger: function (res) {
                // 不要嘗試在trigger中使用ajax異步請求修改本次分享的內容,因爲客戶端分享操作是一個同步操作,這時候使用ajax的回包會還沒有返回
                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('已註冊獲取“分享到微博”狀態事件');
    };

    // 2.5 監聽“分享到QZone”按鈕點擊、自定義分享內容及分享接口
    document.querySelector('#onMenuShareQZone').onclick = function () {
        wx.onMenuShareQZone({
            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('用戶點擊分享到QZone');
            },
            complete: function (res) {
                alert(JSON.stringify(res));
            },
            success: function (res) {
                alert('已分享');
            },
            cancel: function (res) {
                alert('已取消');
            },
            fail: function (res) {
                alert(JSON.stringify(res));
            }
        });
        alert('已註冊獲取“分享到QZone”狀態事件');
    };


    // 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();
    };
    // 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 () {
        // 注意:此 Demo 使用 2.7 版本支付接口實現,建議使用此接口時參考微信支付相關最新文檔。
        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',
            signType: 'SHA1', // 注意:新版支付接口使用 MD5 加密
            paySign: 'bd5b1933cda6e9548862944836a9b52e8c9a2b69'
        });
    };

    // 11.3  跳轉微信商品頁
    document.querySelector('#openProductSpecificView').onclick = function () {
        wx.openProductSpecificView({
            productId: 'pDF3iY_m2M7EQ5EKKKWd95kAxfNw',
            extInfo: '123'
        });
    };

    // 12 微信卡券接口
    // 12.1 添加卡券
    document.querySelector('#addCard').onclick = function () {
        wx.addCard({
            cardList: [
                {
                    cardId: 'pDF3iY9tv9zCGCj4jTXFOo1DxHdo',
                    cardExt: '{"code": "", "openid": "", "timestamp": "1418301401", "signature":"f6628bf94d8e56d56bfa6598e798d5bad54892e5"}'
                },
                {
                    cardId: 'pDF3iY9tv9zCGCj4jTXFOo1DxHdo',
                    cardExt: '{"code": "", "openid": "", "timestamp": "1418301401", "signature":"f6628bf94d8e56d56bfa6598e798d5bad54892e5"}'
                }
            ],
            success: function (res) {
                alert('已添加卡券:' + JSON.stringify(res.cardList));
            },
            cancel: function (res) {
                alert(JSON.stringify(res))
            }
        });
    };

    var codes = [];
    // 12.2 選擇卡券
    document.querySelector('#chooseCard').onclick = function () {
        wx.chooseCard({
            cardSign: '1fdb2640c60e41f8823e9f762e70c531d161ae76',
            timestamp: 1437997723,
            nonceStr: 'k0hGdSXKZEj3Min5',
            success: function (res) {
                res.cardList = JSON.parse(res.cardList);
                encrypt_code = res.cardList[0]['encrypt_code'];
                alert('已選擇卡券:' + JSON.stringify(res.cardList));
                decryptCode(encrypt_code, function (code) {
                    codes.push(code);
                });
            },
            cancel: function (res) {
                alert(JSON.stringify(res))
            }
        });
    };

    // 12.3 查看卡券
    document.querySelector('#openCard').onclick = function () {
        if (codes.length < 1) {
            alert('請先使用 chooseCard 接口選擇卡券。');
            return false;
        }
        var cardList = [];
        for (var i = 0; i < codes.length; i++) {
            cardList.push({
                cardId: 'pDF3iY9tv9zCGCj4jTXFOo1DxHdo',
                code: codes[i]
            });
        }
        wx.openCard({
            cardList: cardList,
            cancel: function (res) {
                alert(JSON.stringify(res))
            }
        });
    };

    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);

    function decryptCode(code, callback) {
        $.getJSON('/jssdk/decrypt_code.php?code=' + encodeURI(code), function (res) {
            if (res.errcode == 0) {
                codes.push(res.code);
            }
        });
    }
});

wx.error(function (res) {
    alert(res.errMsg);
});    

ok,這樣就好了,同時在做開發的時候也發現了一個問題,如何從微信的各個頁面直接返回到微信主頁面呢?

直接調用

WeixinJSBridge.call('closeWindow');

/*關閉頁面 返回微信公衆號主頁面 pc端報錯 微信版無錯*/

今天天附上demo地址:

http://203.195.235.76/jssdk/

就ok了 親測有效

 

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