微信小程序使用webView集成JsSdk出现错误

1.需求

项目中需要使用小程序加载地图显示高清影像,但是微信小程序使用的腾讯地图无法满足,所以使用了第三方自己搭建的地图服务时候需要用的微信jsdk中的wx.getLocation接口

2.技术

1.webView

2.js sdk

3.解决办法配置

  1. 登录https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index注册测试号,注意js接口安全域名一定不要填写带(http头或者https的头,这个坑了我很久,正常的域名即可:baidu.com
    image.png
  1. 第二步获取access_token

    {
        "grant_type": "client_credential", 
        "appid": "测试id", 
        "secret": "测试secret"
    }
    
image.png
  1. 访问getticket方法获取认证ticket![image-20251105094605704]
    image.png

4.程序开发

<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script src="js/crypto-js.min.js"></script>   去下载一个这个js
<script src="js/vconsole.min.js"></script>


function initWeChatSDK() {
        if (typeof wx === 'undefined') {
            console.warn('微信JS-SDK未加载');
            return;
        }

        try {
            // 生成nonceStr(随机字符串)
            const nonceStr = generateNonceStr(16);

            // 生成timestamp(当前时间戳,秒级)
            const timestamp = Math.floor(Date.now() / 1000);

            // 获取jsapi_ticket(需要从后端获取)
            // TODO: 替换为你的后端接口地址
            // const jsapiTicket = await getJsApiTicket();
            const jsapiTicket = "你的Ticket";

            if (!jsapiTicket) {
                console.error('获取jsapi_ticket失败');
                return;
            }

            // 生成signature
            const signature = generateSignature(jsapiTicket, nonceStr, timestamp);

            console.log('微信JS-SDK配置参数:', {
                appId: '你的测试号appid',
                timestamp: timestamp,
                nonceStr: nonceStr,
                signature: signature,
                url: getCurrentUrl()
            });

            // 配置微信JS-SDK
            wx.config({
                debug: false, 
                appId: '你的测试号appid',
                timestamp: timestamp,
                nonceStr: nonceStr,
                signature: signature,
                jsApiList: ['getLocation']
            });

            wx.ready(function () {
                console.log('微信JS-SDK初始化成功');
                getCurrentLocation();
            });

            wx.error(function (res) {
                console.error('微信JS-SDK初始化失败', res);
            });
        } catch (error) {
            console.error('初始化微信JS-SDK时出错:', error);
        }
    }

    function getCurrentLocation() {
        console.log("调用getLocation方法获取位置")
        // 使用微信getLocation API
        wx.getLocation({
            type: 'wgs84', // 返回gcj02坐标系,适用于腾讯地图、高德地图
            //altitude: true, // 是否返回高度信息
            success: function (res) {
                console.log('微信获取位置成功' + res);
                userLocation = {
                    latitude: res.latitude,
                    longitude: res.longitude,
                    accuracy: res.accuracy,
                    altitude: res.altitude || 0,
                    speed: res.speed || 0,
                    timestamp: res.timestamp || Date.now()
                };

                handleLocationSuccess();
            },
            fail: function (err) {
                // console.error('微信获取位置失败', err);
                alert('获取位置失败:' + (err.errMsg || '未知错误'));
            },
        });
    }

 // 生成随机字符串(用于nonceStr)
    function generateNonceStr(length) {
        length = length || 16;
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let result = '';
        for (let i = 0; i < length; i++) {
            result += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return result;
    }

 // 生成微信JSSDK签名
    // 参数:jsapi_ticket(从后端获取的ticket),noncestr(随机字符串),timestamp(时间戳),url(当前页面URL)
    function generateSignature(jsapiTicket, nonceStr, timestamp, url) {
        // 如果没有提供url,使用当前页面URL
        if (!url) {
            url = getCurrentUrl();
        }

        // 构建参数字典(所有参数名均为小写)
        const params = {
            jsapi_ticket: jsapiTicket,
            noncestr: nonceStr,
            timestamp: timestamp.toString(),
            url: url
        };

        // 按照字段名的ASCII码从小到大排序(字典序)
        const sortedKeys = Object.keys(params).sort();

        // 使用URL键值对格式拼接成字符串
        const string1 = sortedKeys.map(key => {
            return key + '=' + params[key];
        }).join('&');

        console.log('签名原始字符串:', string1);

        // 对string1作sha1加密
        const signature = sha1WithCryptoJS(string1);

        console.log('生成的签名:', signature);

        return signature;
    }
    function sha1WithCryptoJS(message) {
        return CryptoJS.SHA1(message).toString(CryptoJS.enc.Hex);
    }
image.png

5.参考资料

image.png
  • 5.微信小程序开发工具切换网页调试开发


    image.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容