H5项目在微信公众号中如何本地调试微信sdk

微信网页开发 /JS-SDK说明文档

1. 申请测试账号

2. 创建Node服务获取access_tokenjsapi_ticket

这两个接口好像只能在服务端调

  • 第一步执行node init -y,再安装对应插件express

  • 第二步创建 service.js

    js 复制代码
    // service.js
    const express = require('express');
    const crypto = require('crypto');
    const axios = require('axios');
    //我这边使用了中间件
    var cors = require('cors');
    
    // 创建 Express 应用实例
    const app = express();
    
    // 创建路由器实例
    const router = express.Router();
    
    // 启用 JSON 请求体解析
    app.use(express.json());
    
    app.use(cors());
    
    // 设置路由
    router.post('/wx-signature', async (req, res) => {
        try {
            const url = decodeURIComponent(req.body.url); // 初始化jsdk的页面url,如果是单页应用记得截掉url的#部分
            console.log(url);
    
            const appId = '你的Appid';
            const appSecret = '你的密钥';
    
            // 获取 access_token
            const tokenRes = await axios.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`);
    
            // 获取 jsapi_ticket
            const ticketRes = await axios.get(`https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${tokenRes.data.access_token}&type=jsapi`);
    
            // 生成签名
            const nonceStr = Math.random().toString(36).substr(2, 15);
            const timestamp = Math.floor(Date.now() / 1000);
            const str = `jsapi_ticket=${ticketRes.data.ticket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${url}`;
            const signature = crypto.createHash('sha1').update(str).digest('hex');
    
            res.json({ appId, timestamp, nonceStr, signature, ticketRes: ticketRes.data.ticket, url });
        } catch (error) {
            console.error('签名生成失败:', error);
            res.status(500).json({
                error: '签名生成失败',
                details: error.response?.data || error.message
            });
        }
    });
    
    // 将路由挂载到应用
    app.use('/api', router); // 现在可以通过 /api/wx-signature 访问
    
    // 启动服务器
    const PORT = process.env.PORT || 70;
    app.listen(PORT, () => {
        console.log(`Node服务已启动,端口: ${PORT}`);
        console.log(`签名API地址: http://localhost:${PORT}/api/wx-signature`);
    });
  • 第三步执行node service.js启动服务

3. Uniapp前端代码

uniapp对wx方法进行了重写,所以单独引sdk,但是在index.html直接引又会有问题

js 复制代码
// /utils/wx-sdk
import jWeixin from '@/static/js/jweixin-module';
export const initWxSDK = () => {
    return new Promise(async (resolve, reject) => {
        // 确保wx对象存在
        // 检查是否在微信环境
        // if (!isWeixin()) {
        //     console.log('请在微信中打开此页面');
        //     return;
        // }
        if (typeof jWeixin === 'undefined') {
            reject('微信JS-SDK未加载,请检查引入');
        }
        // const data = {
        //     appId: '',
        //     timestamp: 1750385102,
        //     nonceStr: 'iph3vbbxzr',
        //     signature: 'd5773d32db2e1258356cb7c98c4f867a1b423b87'
        // };
        // const { appId, timestamp, nonceStr, signature } = data;
        // // 从后端获取签名配置
        // jWeixin.config({
        //     debug: false,
        //     appId,
        //     timestamp,
        //     nonceStr,
        //     signature,
        //     jsApiList: ['startFacialRecognitionVerify'] // 需要使用的 API
        // });

        // jWeixin.ready(() => {
        //     // alert('微信 SDK 初始化成功');
        //     uni.hideLoading();
        //     resolve(jWeixin);
        // });

        // jWeixin.error(err => {
        //     alert('微信 SDK 初始化失败' + JSON.stringify(err));
        //     reject(err);
        // });
        const url = encodeURIComponent(window.location.href.split('#')[0]); //当前网页的URL,不包含#及其后面部分
        console.log(url);

        uni.request({
            url: 'http://localhost:70/api/wx-signature',
            method: 'POST',
            data: { url },
            success: res => {
                const { appId, timestamp, nonceStr, signature } = res.data;
                jWeixin.config({
                    debug: false,
                    appId,
                    timestamp,
                    nonceStr,
                    signature,
                    jsApiList: ['startFacialRecognitionVerify', 'downloadImage'] // 需要使用的 API
                });

                jWeixin.ready(() => {
                    console.log('微信 SDK 初始化成功');
                    uni.hideLoading();
                    resolve(jWeixin);
                });

                jWeixin.error(err => {
                    console.log('微信 SDK 初始化失败' + err);
                    reject(err);
                });
            },
            //响应失败
            fail: err => {
                reject(err);
            }
        });
    });
};

// 人脸识别方法
export const faceRecognition = (name, idCard) => {
    return new Promise((resolve, reject) => {
        alert(jWeixin.startFacialRecognitionVerify);
        resolve(true);

        // jWeixin.startFacialRecognitionVerify({
        //     name,
        //     idCardNumber: idCard,
        //     success: res => resolve(res.verifyResult),
        //     fail: err => reject(err)
        // });
    });
};
// utils/env-check.js
export function isWeixin() {
    // 非 H5 环境直接返回 false
    // #ifndef H5
    return false;
    // #endif

    // H5 环境下检查用户代理
    // #ifdef H5
    const ua = window.navigator.userAgent.toLowerCase();

    const isWeixin = /micromessenger/i.test(ua);

    // 额外检查是否在微信内置浏览器中打开(公众号核心特征)
    if (isWeixin) {
        // 公众号环境会注入 WeixinJSBridge
        return typeof window.WeixinJSBridge !== 'undefined';
    }
    return false;
    // #endif
}

组件内调用

js 复制代码
<!-- 人脸识别 -->
<template>
    <u-button @click="startFaceRecognition">人脸</u-button>
</template>

<script>
import { initWxSDK, faceRecognition } from '@/utils/wx-sdk';
export default {
    data() {
        return {
            wxSDK: null
        };
    },
    async mounted() {
        try {
            this.wxSDK = await initWxSDK();
            console.log(this.wxSDK);
        } catch (e) {
            alert(JSON.stringify(e));
            console.log(e);

            // uni.showToast({ title: '微信初始化失败', icon: 'none' });
        }
    },
    methods: {
        async startFaceRecognition() {
            if (!this.wxSDK) {
                uni.showToast({ title: '请稍后重试', icon: 'none' });
                return;
            }

            try {
                const verifyResult = await faceRecognition('张三', '110101199003071234');
                console.log();

                // 将结果发送到后端二次验证
                const res = await uni.request({
                    url: 'https://your-server.com/verify-result',
                    method: 'POST',
                    data: { verifyResult }
                });

                //  this.result = res.data.success ? '验证通过' : '验证失败';
            } catch (err) {
                console.error(err);
                // this.result = `失败: ${err.errMsg || '未知错误'}`;
            }
        }
    }
};
</script>

<style lang="less" scoped></style>

4. 启动

  • 打开微信开发者工具,选择微信网页

相关推荐
前端早间课1 小时前
微信小程序获取指定元素,滚动页面到指定位置
微信小程序·小程序
默默地写代码1 小时前
微信小程序 新版canvas绘制名片
前端·javascript·微信小程序
小糊涂加油1 小时前
微信小程序canvas实现抽奖动画
微信小程序·小程序
38kcok9w2vHanx_1 小时前
微信小程序form表单手机号正则检验pattern失效
微信小程序·小程序
Asurplus2 小时前
【微信小程序】4、SpringBoot整合WxJava生成小程序码
spring boot·微信小程序·wxjava·小程序码
天和都成7 小时前
微信小程序出现冒泡问题的原因和解决方法
微信小程序
Q_Q5110082857 小时前
python+uniapp基于微信小程序健康管理系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
云起SAAS8 小时前
猜数字小游戏微信流量主小程序开源
微信·小程序·猜数字小游戏微信流量主小
云起SAAS8 小时前
经典俄罗斯方块微信小游戏流量主小程序开源
微信·小程序·经典俄罗斯方块微信小游戏流