一 開發流程
1 基本配置-登錄自己的公眾號
A:新型微信認證,認證過的企業號才可以進行自定義菜單中的連接跳轉;
B:開發基本配置里面進行開發者iD查詢,密碼查詢和重置和ip白名單配置;
C:公眾號設置里面有功能設置,將自己的業務域名,js接口安全域名 網頁授權域名陪置相同(改域名必須可以外網訪問的),而且非80 和443接口不可以(不能有端口號,使用默認的端口號是可以的),域名證書可以放在域名執行的靜態文件夾里面dist;(此配置可以開發完成后配置,可以先用測試號進行測試和開發)

2 測試號的使用和配置
A:登錄微信公眾賬號 ----> 公眾平台測試賬號申請 ----> 添加測試賬號,下次登錄進入直接是測試賬號的一些信息,賬號內部二維碼掃面既可關注測試的公眾號進行開發和調試
B:自定義菜單配置
技術文檔 ----> 自定義菜單 ----> 自定義菜單創建接口(內含詳細的配置接口的方法和說明)最下面使用網頁調試工具調試改接口 ----> 進入后接口類型
先選擇基礎支持獲取相應的access_token ----> 在選自定義菜單(按需要進行添加數據 body數據如下示例)
"button": [
{
"type": "view",
"name": "正式",
"url": "(前面必須加http)正式域名[/項目名]"
},
{
"type": "view",
"name": "測試",
"url": "http://測試域名/項目名"
},
{
"type": "view",
"name": "本地",
"url": "http://本機ip/項目名"
}
]
}

最后用測試號掃二維碼,就可以了
C:域名配置,以上配置完成還不能正常訪問,需要配置js域名和回掉域名,在測試號內部將js安全域名和回掉域名設置為相同的既可;

二 微信sdk的使用
A:新進行微信的授權登錄
B:微信認證
C:相關方法的使用
如下代碼的整體過程:相關信息請查閱技術文檔
// 可先使用測試號的進行測試 ,代碼中的kit 為自定義的工具方法
var AppId = YOURAPPID;
// 微信授權實際是頁面跳轉,跳轉過程中會存在code,獲取code成功向后台發起請求獲取openId和微信認證的簽名和對應的生成簽名的時間戳和隨機字符串(非靜默授權方可拿到用戶信息,以下以非靜默授權為例)
//獲取url中的code值 和當前的url(#之前,具體參數詳見技術文檔js-SDK使用說明)
var code = this.Kit.getUrlParam('code');
var local = window.location.href;
var Signature = '' ,Timestamp = '' , NonceStr ='' ;
function authWechat(){
if(code == null || code == ''){
//拿不到code,刷新頁面繼續
window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+AppId+'&redirect_uri='+encodeURIComponent(local)+'&response_type=code&scope=snsapi_userinfo&state=1&wechat_redirect';
}else{
var params = {
code:code,
pageUrl:getCrtUrl()
}
_self.Kit.ajax({
url: '接口url',
method:'POST',
body: params,
success: function(res){
if(res.code == 200){
localStorage.setItem('openId',res.data.openid);
localStorage.setItem('signatrue',res.data.signatrue);
Signature = res.data.signature;
Timestamp = res.data.timestamp;
NonceStr = res.data.noncestr;
//進行認證
wxConfig();
}
},
error: function(error){
},
last: function(){
}
})
}
}
authWechat()
function getCrtUrl(){
var temp = window.location.href;
var end = temp.indexOf('#');
if(end!=-1){
return temp.substring(0,end);
}else{
return temp
}
}
// 認證
function wxConfig(){
wx.config({
debug: true,// 開啟調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時才會打印。
appId: AppId, // 必填,公眾號的唯一標識
timestamp: Timestamp, // 必填,生成簽名的時間戳
nonceStr: NonceStr, // 必填,生成簽名的隨機串
signature: Signature,// 必填,簽名
jsApiList: ['openLocation','getLocation','closeWindow','checkJsApi'] //
});
var latitude;
var longitude;
var speed;
var accuracy;
wx.ready(function(){
wx.checkJsApi({
jsApiList: ['getLocation'], // 需要檢測的JS接口列表,所有JS接口列表見附錄2,
success: function(res) {
alert('dsgsdag' + res.checkResult.getLocation);
if (res.checkResult.getLocation == false) {
alert("你的微信版本太低,不支持微信JS接口,請升級到最新的微信版本!");
return;
}
}
});
// config信息驗證后會執行ready方法,所有接口調用都必須在config接口獲得結果之后,config是一個客戶端的異步操作,所以如果需要在頁面加載時就調用相關接口,則須把相關接口放在ready函數中調用來確保正確執行。對於用戶觸發時才調用的接口,則可以直接調用,不需要放在ready函數中。
// 以認證成功進行定位為例說明;
try {
wx.getLocation({
success : function(res) {
alert('getLoc success');
latitude = res.latitude; // 緯度,浮點數,范圍為90 ~ -90
longitude = res.longitude; // 經度,浮點數,范圍為180 ~ -180。
/* speed = res.speed; // 速度,以米/每秒計 */
accuracy = res.accuracy; // 位置精度
baiduGeo(latitude,longitude);
},
fail : function(res) {
alert('wx.getL fail');
_self.$dialog.alert({
message: '定位失效,請手動選擇'
}).then(function(){
_self.$router.push('location');
})
},
cancel: function (res) {
alert('getLoc cancel');
wx.closeWindow();
},
complete:function(res){
alert('complete');
}
});
}
catch(e) {
alert(e);
}
});
wx.error(function(res){
// config信息驗證失敗會執行error函數,如簽名過期導致驗證失敗,具體錯誤信息可以打開config的debug模式查看,也可以在返回的res參數中查看,對於SPA可以在這里更新簽名。
_self.$dialog.alert({
message: '微信認證失敗,請重試'
}).then(function(){
wx.closeWindow();
})
});
function baiduGeo(latitude,longitude){
//baidu
var latlon = latitude +','+longitude;
var urlBaidu = "http://api.map.baidu.com/geocoder/v2/?ak=C93b5178d7a8ebdb830b9b557abce78b&callback=renderReverse&location="+latlon+"&output=json&pois=0";
_self.$http.jsonp(urlBaidu).then(function(res){
var res = JSON.parse(res.bodyText);
var locIso = res.result.addressComponent.country_code_iso;
_self.position_loc = res.result.addressComponent.country;
if(_self.position_loc !='Mali'){
_self.$dialog.confirm({
message: '根據定位,您所在的區域尚未開放服務,是否手動選擇區域'
}).then(function(){
localStorage.setItem('position_loc',res.result.addressComponent.country_code_iso);
_self.$router.push('location');
},function(){
wx.closeWindow();
}).catch(function(){
});
}else{
localStorage.setItem('position_loc',_self.Kit.getCountryMcc(locIso));
_self.$router.push('home');
}
},function(res){
_self.$dialog.alert({
message: '定位系統失效,請手動選擇'
}).then(function(){
_self.$router.push('location');
})
})
}
}
4 開發中遇到的問題和解決方法
問題1: js引入問題,我將http://res.wx.qq.com/open/js/jweixin-1.2.0.js的js文件下載到本地在引入 不能成功的引入,會報wx is not undefined;
解決:直接利用網絡請求既可,無需下載到本地在引入;
問題2:invalid url domain 以及1003問題,是j前面介紹的s域名與當前網址域名不一致造成的
解決:正確配置一致的域名(可本地ip地址,只要3處保持一致既可)
三 簽名算法的實現
js ticket簽名算法 利用js實現時使用jsonp請求,不能正確的獲取到數據,具體算法如下:
function getSign(tic,ranstr,tim,urlt){
var string1 = "jsapi_ticket"+tic+'&noncestr='+ranstr+'×tamp='+tim +'&url='+urlt;
return sha(string1);
}
function sha(ticket){
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
function hex_sha1(s) {
return binb2hex(core_sha1(str2binb(s), s.length * chrsz));
}
function b64_sha1(s) {
return binb2b64(core_sha1(str2binb(s), s.length * chrsz));
}
function str_sha1(s) {
return binb2str(core_sha1(str2binb(s), s.length * chrsz));
}
function hex_hmac_sha1(key, data) {
return binb2hex(core_hmac_sha1(key, data));
}
function b64_hmac_sha1(key, data) {
return binb2b64(core_hmac_sha1(key, data));
}
function str_hmac_sha1(key, data) {
return binb2str(core_hmac_sha1(key, data));
}
/*
* Perform a simple self-test to see if the VM is working
*/
function sha1_vm_test() {
return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
}
/*
* Calculate the SHA-1 of an array of big-endian words, and a bit length
*/
function core_sha1(x, len) {
/* append padding */
x[len >> 5] |= 0x80 << (24 - len % 32);
x[((len + 64 >> 9) << 4) + 15] = len;
var w = Array(80);
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
var e = -1009589776;
for (var i = 0; i < x.length; i += 16) {
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
var olde = e;
for (var j = 0; j < 80; j++) {
if (j < 16) w[j] = x[i + j];
else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
e = d;
d = c;
c = rol(b, 30);
b = a;
a = t;
}
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
e = safe_add(e, olde);
}
return Array(a, b, c, d, e);
}
/*
* Perform the appropriate triplet combination function for the current
* iteration
*/
function sha1_ft(t, b, c, d) {
if (t < 20) return (b & c) | ((~b) & d);
if (t < 40) return b ^ c ^ d;
if (t < 60) return (b & c) | (b & d) | (c & d);
return b ^ c ^ d;
}
/*
* Determine the appropriate additive constant for the current iteration
*/
function sha1_kt(t) {
return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514;
}
/*
* Calculate the HMAC-SHA1 of a key and some data
*/
function core_hmac_sha1(key, data) {
var bkey = str2binb(key);
if (bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);
var ipad = Array(16),
opad = Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
return core_sha1(opad.concat(hash), 512 + 160);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function rol(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* Convert an 8-bit or 16-bit string to an array of big-endian words
* In 8-bit function, characters >255 have their hi-byte silently ignored.
*/
function str2binb(str) {
var bin = Array();
var mask = (1 << chrsz) - 1;
for (var i = 0; i < str.length * chrsz; i += chrsz)
bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i % 32);
return bin;
}
/*
* Convert an array of big-endian words to a string
*/
function binb2str(bin) {
var str = "";
var mask = (1 << chrsz) - 1;
for (var i = 0; i < bin.length * 32; i += chrsz)
str += String.fromCharCode((bin[i >> 5] >>> (24 - i % 32)) & mask);
return str;
}
/*
* Convert an array of big-endian words to a hex string.
*/
function binb2hex(binarray) {
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for (var i = 0; i < binarray.length * 4; i++) {
str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF);
}
return str;
}
/*
* Convert an array of big-endian words to a base-64 string
*/
function binb2b64(binarray) {
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str = "";
for (var i = 0; i < binarray.length * 4; i += 3) {
var triplet = (((binarray[i >> 2] >> 8 * (3 - i % 4)) & 0xFF) << 16) | (((binarray[i + 1 >> 2] >> 8 * (3 - (i + 1) % 4)) & 0xFF) << 8) | ((binarray[i + 2 >> 2] >> 8 * (3 - (i + 2) % 4)) & 0xFF);
for (var j = 0; j < 4; j++) {
if (i * 8 + j * 6 > binarray.length * 32) str += b64pad;
else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F);
}
}
return str;
}
return hex_sha1(ticket)
}
function getTicket(){
var urlGetTkt = "http://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+_self.ACCESS_TOKEN+"&type=jsapi";
_self.$http.jsonp(urlGetTkt).then(
function(res){
res = JSON.parse(res);
_self.TICKET = res.ticket;
alert(res.ticket);
},
function(res){
console.log(res);
_self.$dialog.alert({
message: 'get ticket failure'
});
}
)
}
function getCrtUrl(){
var temp = window.location.href;
var end = temp.indexOf('#');
if(end!=-1){
return temp.substring(0,end);
}else{
return temp
}
}
getTicket()
_self.signature=getSign(_self.TICKET,_self.randomStr,_self.timestamp,getCrtUrl());
getTicket()時 一直在走失敗的回掉 不知道具體是什么原因???? 如有大神請私信我,非常感謝
實際上簽名算法是有安全性限制的,需要服務器端處理,在通過ajax傳遞給web端
