綁定域名
- 登錄微信公眾平臺進入“公眾號設置”的“功能設置”里填寫“JS接口安全域名”
Vue項目引入微信JS-sdk
- 方式一:使用
npm install weixin-js-sdk
- 方式二:在vue項目下public文件夾下的index.html頁面,引入微信配置文件
····
<!-- 引入微信配置文件 -->
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
····
權(quán)限配置
- 通過
config
接口注入權(quán)限驗證配置
所有需要使用 JS-SDK 的頁面必須先注入配置信息茴肥,否則將無法調(diào)用(同一個 url 僅需調(diào)用一次击蹲,對于變化 url 的 SPA 的 web app 可在每次 url 變化時進行調(diào)用,目前 Android 微信客戶端不支持 pushState 的 H5 新特性试吁,所以使用 pushState 來實現(xiàn) web app 的頁面會導致簽名失敗纯丸,此問題會在 Android6.2 中修復)苛聘。
wx.config({
debug: true, // 開啟調(diào)試模式,調(diào)用的所有api的返回值會在客戶端alert出來滔吠,在pc端時會打印医吊。
appId: '', // 必填,公眾號的唯一標識
timestamp: , // 必填贾陷,生成簽名的時間戳
nonceStr: '', // 必填缘眶,生成簽名的隨機串
signature: '', // 必填,簽名
jsApiList: [], // 必填髓废,需要使用的JS接口列表
openTagList: ['wx-open-launch-weapp'] // 微信開放標簽
})
- 通過
ready
接口處理成功驗證
wx.ready(function(){
// config信息驗證后會執(zhí)行ready方法巷懈,所有接口調(diào)用都必須在config接口獲得結(jié)果之后,
// config是一個客戶端的異步操作慌洪,所以如果需要在頁面加載時就調(diào)用相關(guān)接口顶燕,則須把相關(guān)接口放在ready函數(shù)中調(diào)用來確保正確執(zhí)行凑保。
// 對于用戶觸發(fā)時才調(diào)用的接口,則可以直接調(diào)用涌攻,不需要放在ready函數(shù)中欧引。
});
- 通過
error
接口處理失敗驗證
wx.error(function(res){
// config信息驗證失敗會執(zhí)行error函數(shù),
// 如簽名過期導致驗證失敗恳谎,具體錯誤信息可以打開config的debug模式查看芝此,也可以在返回的res參數(shù)中查看,對于SPA可以在這里更新簽名因痛。
});
項目中封裝JS-SDK config 方法
// /utils/wechat.js
import wx from 'weixin-js-sdk'
import getSignature from '@/api'
/**
* @description 微信config方法封裝
* @param {string} url 授權(quán)網(wǎng)頁鏈接
* @param {array} apiList 使用的JS接口列表
* @param {array} openTagList 使用的開放標簽列表
* @returns Promise
*/
export function weixinAuth ( url, apiList = ['wx-open-launch-weapp', 'getLocation', 'openLocation'] openTagList = ['wx-open-launch-weapp']) {
if (!is_weixn()) {
return
}
return new Promise((resolve,reject) => {
getSignature({ url }).then(res => {
if (res.appId) {
wx.config({
debug: false,
appId: res.appId,
timestamp: res.timeStamp,
nonceStr: res.nonceStr,
signature: res.signature,
jsApiList: apiList,
openTagList: openTagList
})
wx.ready(res => {
resolve(res, wx)
})
}
}).catch(err => {
reject(err)
})
})
}
/**
* @description 判斷使用終端是否為IOS
* @returns Boolean
*/
export function isIOS () {
const isIphone = navigator.userAgent.includes('iPhone')
const isIpad = navigator.userAgent.includes('iPad')
return isIphone || isIpad
}
/**
* @description 判斷是否微信環(huán)境
* @returns Boolean
*/
function is_weixn() {
let ua = navigator.userAgent.toLowerCase()
if (ua.match(/MicroMessenger/i) == 'micromessenger') {
return true
} else {
return false
};
};
頁面中調(diào)用
- 單獨頁面的使用
import { weixinAuth } from '@/utils/wechat'
export default {
create(){
const url = window.location.href
weixinAuth(url)
}
}
- 全局引用
import { weixinAuth, isIOS } from '@/utils/wechat'
router.beforeEach(async (to, from, next) => {
// 路由守衛(wèi)處理IOS
if (isIOS()) {
if (from.path === '/') {
weixinAuth婚苹,isIOS({ url: location.href.split('#')[0] })
}
}
})
JS-SDK簽名算法--后端生成
- appId 和 appsecret 只需登錄“微信公眾平臺”--“開發(fā)”--“基本設置”
- url則是前臺傳過來的當前頁面的地址值
- access_token獲取
public String getAccessToken(String appId , String appSecret){
// 網(wǎng)頁授權(quán)接口
String GetPageAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret;
HttpClient client = null;
String access_token = null;
int expires_in = 0;
try {
client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(GetPageAccessTokenUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = client.execute(httpget, responseHandler);
JSONObject OpenidJSONO = JSONObject.fromObject(response);
access_token = String.valueOf(OpenidJSONO.get("access_token"));//獲取access_token
expires_in = Integer.parseInt(String.valueOf(OpenidJSONO.get("expires_in")));//獲取時間
} catch (Exception e) {
throw new CommonRuntimeException("獲取AccessToken出錯!");
} finally {
client.getConnectionManager().shutdown();
}
return access_token;
}
- 獲取jsapi_ticket
public String getTicket(String accessToken) {
// 網(wǎng)頁授權(quán)接口
String GetPageAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+accessToken+"&type=jsapi";
HttpClient client = null;
String ticket = "";
int expires_in = 0;
try {
client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(GetPageAccessTokenUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = client.execute(httpget, responseHandler);
JSONObject OpenidJSONO = JSONObject.fromObject(response);
ticket = String.valueOf(OpenidJSONO.get("ticket"));//獲取ticket
expires_in = Integer.parseInt(String.valueOf(OpenidJSONO.get("expires_in")));//獲取時間
} catch (Exception e) {
throw new CommonRuntimeException("獲取Ticket出錯鸵膏!");
} finally {
client.getConnectionManager().shutdown();
}
return ticket;
}
- SHA1加密膊升,參數(shù)是由url、jsapi_ticket谭企、noncestr廓译、timestamp組合而成
public String SHA1(String str) {
try {
MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1"); //如果是SHA加密只需要將"SHA-1"改成"SHA"即可
digest.update(str.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexStr = new StringBuffer();
// 字節(jié)數(shù)組轉(zhuǎn)換為 十六進制 數(shù)
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
if (shaHex.length() < 2) {
hexStr.append(0);
}
hexStr.append(shaHex);
}
return hexStr.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
4.獲取 Signature
public String getSignature(String url) {
String signature = "";
String appid = *********;//微信公眾號的appid
String appsecret = ***********;//微信公眾號的appsecret
//獲取noncestr
String noncestr = UUID.randomUUID().toString();
//獲取timestamp
String timestamp = Long.toString(System.currentTimeMillis() / 1000);
//獲取access_token
String access_token = getAccessToken(appid , appsecret);
//獲取jspai_ticket
String jsapi_ticket = getTicket(access_token);
//將四個數(shù)據(jù)進行組合,傳給SHA1進行加密
String str = "jsapi_ticket=" + jsapi_ticket +
"&noncestr=" + noncestr +
"×tamp=" + timestamp +
"&url=" + url;
//sha1加密
signature = SHA1(str);
return signature ;
}
JS-SDK 接口赞咙、開放標簽使用
自定義“分享給朋友”及“分享到QQ”按鈕的分享內(nèi)容
import weixinAuth from '@/utils/wechat'
export default {
methods:{
shareFriends () {
weixinAuth().then((res, wx) => {
wx.updateAppMessageShareData({
title: '', // 分享標題
desc: '', // 分享描述
link: '', // 分享鏈接责循,該鏈接域名或路徑必須與當前頁面對應的公眾號JS安全域名一致
imgUrl: '', // 分享圖標
success: function () {
// 設置成功
}
})
})
}
}
}
公眾號打開小程序
基本用法
<template>
<wx-open-launch-weapp
id="launch-btn"
:username="weapp.username"
:path="weapp.path"
@launch="handleLaunchFn"
@error="handleErrorFn"
>
<script type="text/wxtag-template">
<style>
.test-btn{
width:100%;
background: #f24f45;
border-radius: 20px;
padding:0 10px;
color:#fff;
font-size:16px;
border:none;
}
</style>
<button class="test-btn">點我跳轉(zhuǎn)小程序</button>
</script>
</wx-open-launch-weapp>
</template>
<script>
import { weixinAuth } from '@/utils/wechat'
export default {
created () {
const url = window.location.href
wechatUtil.initWechat({ url })
},
}
</script>
使用動態(tài)生成標簽
- 封裝 動態(tài)生成微信開放標簽(wx-open-launch-weapp)方法
/**
* @description 動態(tài)生成微信發(fā)放標簽
* @param { object:{
* appid {string} 小程序原始id(gh_xxxxxxx)
* url {string} 小程序跳轉(zhuǎn)路徑 例 pages/home/home.html - (后面必須帶上.html后綴 否則IOS跳轉(zhuǎn)時出現(xiàn)小程序頁面未配置)
* eleId {string} 元素id
* content {string} html字符串
* }} info
**/
export function openLaunchWeapp(info) {
if(!is_weixin()){
return false
}
if(is_version()){
var btn = document.getElementById(info.eleId)
let script = document.createElement('script')
script.type = "text-wxtag-template"
script.text = info.content
let html = `
<wx-open-launch-weapp style="width:100%;display:block;" username="${info.appid}" path="${info.url}">
${script.outerHTML}
</wx-open-launch-weapp>`
btn.innerHTML = html
btn.addEventlistener('launch', function (e) {
console.log('success')
})
btn.addEventListener('error',function (e) {
console.log('fail',e.detail)
alert(`跳轉(zhuǎn)異常-${e.detail}`)
})
} else {
alert(`您的版本不支持跳轉(zhuǎn)小程序`)
}
}
// 判斷是否微信環(huán)境
function is_weixn() {
let ua = navigator.userAgent.toLowerCase()
if (ua.match(/MicroMessenger/i) == 'micromessenger') {
return true
} else {
return false
};
};
// 判斷當前微信版本號是否支持--使用微信開放標簽
export function is_version(){
let client = false; // 當前版本號是否支持 (默認不支持)
let wxInfo = navigator.userAgent.match(/MicroMessenger\/([\d\.]+)/i); // 微信瀏覽器信息
// 微信版本號 wxInfo[1] = "7.0.18.1740" (示例)
//進行split轉(zhuǎn)成數(shù)組進行判斷 [7,0,18,1740] (示例)
let version = wxInfo[1].split(".");
// 判斷版本在7.0.12及以上的版本
if (version[0] >= 7) {
if (version[1] >= 0) {
if (version[2] >= 12) {
client = true; // 當前版本支持
}
}
}
return client;
}
- 頁面中使用
<template>
<div id="launch-btn"></div>
</template>
<script>
import { openLaunchWeapp } from '@/utils/wechat'
export default {
mounted(){
const weappDom = this.$el.querySelector('.weapp-cover')
openLaunchWeapp({
eleId:"launch-btn", // 元素id
appid: 'gh_xxxx', // 小程序原始id
url: 'pages/home/home.html', // 小程序跳轉(zhuǎn)路徑
content: `
<button class="test-btn">點我跳轉(zhuǎn)小程序</button>
<style>
.test-btn{
width:100%;
background: #f24f45;
border-radius: 20px;
padding:0 10px;
color:#fff;
font-size:16px;
border:none;
}
</style>`
})
}
}
</script>