這里給大家分享我在網上總結出來的一些知識,希望對大家有所幫助

在業務中接觸了微信小程式,客戶對引流用戶非常在意,每次都會提該需求,經常做就存檔一下,使用的小程式賬戶都是企業版非個人版本,
跳轉H5
- 在微信公眾平臺-小程式后臺配置業務域名,要將校驗檔案放置到域名根目錄下,才可配置成功,通過
https://url/校驗檔案名.txt可測驗成功與否, - 使用 web-view 配置路徑
- 如需傳參通過
?key=value形式一起傳輸,在另一端接收 URL 上的引數便可,
<web-view :src="https://www.cnblogs.com/smileZAZ/p/`https://url/index.html#/?timestamp=${timestamp}`" />
跳轉小程式
- 參考 navigator ?? 、wx.navigateToMiniProgram ? 、Taro.navigateToMiniProgram ?
// 方式一:似乎不能用了,有哪位好心人能用的話求咨詢
<button @click="goMiniapp">跳轉下載</button>
Taro.navigateToMiniProgram({ // 我用的taro,原生用 wx.navigateToMiniProgram 就行
appId: "appid",
path: 'page/index/index',
extraData: { // 傳遞給小程式的資料
foo: 'bar'
},
envVersion: 'develop',
success(res) {
// 打開成功
}
})
// 方式2:可用,可以回退到自己的小程式
<navigator target="miniProgram" open-type="navigate" app-id="appid" path="pages/index/index">跳轉小程式</navigator>
跳轉App
2021.5 月開始小程式不再支持跳轉到 App,那要怎么跳轉 App 呢,看了一下騰訊視頻的小程式是利用客服訊息發送 App 下載地址,感覺此方法體驗甚好,就參考了很多檔案實測了一下,源地址:關于不再提供“小程式打開App技術服務”的通知
訊息推送配置
?? 訊息推送配置指南 介紹的很清楚,也可以只看這個,
首先要開始微信的訊息推送功能,在微信公眾平臺-小程式后臺-開發管理-訊息推送,選擇啟用,這個部分需要管理員或開發者進行掃碼確認,
確認成功會跳轉到配置頁面,按需求配置即可,我這里選擇了安全模式,會對后續客服訊息
Token驗證
微信服務器將發送 GET 請求到填寫的服務器地址 URL 上,進行 Token 驗證,所以要先新建好服務器并上線,
?? 該圖是關于回傳的引數 + 如何創建 GET 請求

main.mjs 根據設定好的要求,按步驟創建get方法用于接收get請求,這里使用了ES6,需要對 package.json 增加 "type": "module",
import express from "express";
import request from "request"
import cors from "cors";
import bodyparser from "body-parser";
import CryptoJS from "crypto-js";
var app = express();
app.use(cors({ origin: "*" }));
app.use(bodyparser.json());
var config = {
token: 'sxRGsggaA7XaYlSKuKVJkThLs', // 和配置訊息推送的token一致
content: "下載騰訊視頻App,享受更多播放特權,請戳→http://m.v.qq.com/activity/downapp_activity.html", // 借用騰訊下載app的鏈接,做的demo
EncodingAESKey: "你的EncodingAESKey",
APPID: "你的APPID",
APPSECRET: "你的APPSECRET",
access_token: ""
}
app.get("/url", (req, res) => {
console.log(req.query);
var signature = req.query.signature;
var timestamp = req.query.timestamp;
var nonce = req.query.nonce;
var echostr = req.query.echostr;
var ciphertext = CryptoJS.SHA1([config.token, timestamp, nonce].sort().join(''));
if (signature == ciphertext.toString()) {
res.send(echostr);
} else {
res.send({
status: 400,
data: "check msg error"
});
}
});
app.listen(process.env.PORT)
接下來就可以點提交鍵啦~~,成功配置后會跳轉回到開發配置頁面,此時你的相關配置就在這能查看到,
小程式跳轉客服訊息
?? 參考微信組件 button
<button open-type="contact">前方客服會話獲取下載鏈接</button>
配置AccessToken(非安全模式不需要這部)
?? 參考微信介面 getAccessToken
main.mjs
function get_access_token() {
return new Promise((resolve, reject) => {
request(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.APPID}&secret=${config.APPSECRET}`, { json: true }, (err, res, body) => {
if (err) {
reject(err)
} else {
resolve(body)
}
});
})
}
var out_time = 7100 * 1000
var last_time = 0;
async function get_token() {
if (Date.now() - out_time > last_time) {
var cur = await get_access_token()
config.access_token = cur.access_token;
last_time = Date.now();
console.log('當前token:', config.access_token)
console.log('過期時間:', new Date(last_time + out_time).toString(), '+8小時'); // 在服務器部署的是UTC時間,和北京時間差8小時,,
}
return config.access_token;
}
setInterval(get_token, 5000)
get_token();
配置客服自動回復
如非安全模式,參考 ?? 訊息推送回復 就行內部代碼很詳細,
配置選擇安全模式的話,需要對接收資訊進行解密, 以下為 wx-crypto.mjs 解密模塊
import crypto from 'crypto'; // 加密模塊
function decodePKCS7(buff) {
let pad = buff[buff.length - 1];
if (pad < 1 || pad > 32) {
pad = 0;
}
return buff.slice(0, buff.length - pad);
};
// 微信轉發客服訊息解密
function decryptContact(key, iv, crypted) {
const aesCipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
aesCipher.setAutoPadding(false);
let decipheredBuff = Buffer.concat([aesCipher.update(crypted, 'base64'), aesCipher.final()]);
decipheredBuff = decodePKCS7(decipheredBuff);
const lenNetOrderCorpid = decipheredBuff.slice(16);
const msgLen = lenNetOrderCorpid.slice(0, 4).readUInt32BE(0);
const result = lenNetOrderCorpid.slice(4, msgLen + 4).toString();
return result;
};
// 解密微信回傳給配置的訊息服務器的資訊
function decryptWXContact(wechatData, EncodingAESKey) {
if (!wechatData) {
wechatDatahttps://www.cnblogs.com/smileZAZ/p/= '';
}
//EncodingAESKey 為后臺配置時隨機生成的
const key = Buffer.from(EncodingAESKey + '=', 'base64');
const iv = key.slice(0, 16);
const result = decryptContact(key, iv, wechatData);
const decryptedResult = JSON.parse(result);
console.log(decryptedResult);
return decryptedResult;
};
export {decryptWXContact}
main.mjs post方法,接收資訊解密 + 回傳訊息,
import { decryptWXContact } from "./wx-crypto.mjs"
app.post("/url", async (req, res) => {
const { ToUserName, Encrypt } = req.body // ToUserName 推送接收的賬號
if (!Encrypt) return res.send('success'); //配置時選的安全模式 因此需要解密
const decryptData = https://www.cnblogs.com/smileZAZ/p/decryptWXContact(Encrypt, config.EncodingAESKey);
if (!decryptData) return res.send('success');
if (decryptData.MsgType == 'text') {
await sendmess(config.access_token, {
access_token: config.access_token,
touser: decryptData.FromUserName,
msgtype: 'text',
text: {
content: decryptData.Content == '下載' ? config.content || '' : '感謝您關注xxx小程式'
},
image: {},
link: {},
miniprogrampage: {}
})
}
res.send('success') // 不進行任何回復,直接回傳success,告知微信服務器已經正常收到,
});
function sendmess(access_token, mess) {
return new Promise((resolve, reject) => {
var options = {
'method': 'POST',
'url': `https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${config.access_token}`,
'headers': {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"access_token": `${config.access_token}`,
...mess
})
}
request(options, function (error, response) {
if (error) reject(error);
resolve(response.body)
});
})
}
成果

本文轉載于:
https://juejin.cn/post/7155829250547777572
如果對您有所幫助,歡迎您點個關注,我會定時更新技術檔案,大家一起討論學習,一起進步,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/541297.html
標籤:Html/Css
