uniapp微信公众号h5开发 您所在的位置:网站首页 csdn企业招聘公众号 uniapp微信公众号h5开发

uniapp微信公众号h5开发

2023-03-18 21:31| 来源: 网络整理| 查看: 265

微信公众号开发,一站式踩坑

开发前提:例如你们域名是https://www.baidu.com

配置nginx反向代理,把你项目的端口重定向到你们测试环境或线上环境域名 # 访问https://baidu.com 的时候,指向127.0.0.1:8080 #user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; server { listen 80; server_name baidu.com;//替换成你的域名 location / { proxy_pass http://127.0.0.1:8080;//替换你项目的 } } include servers/*; }

修改本地host文件 打开host文件最后一行添加127.0.0.1 baidu.com mac和windows电脑自行百度打开host方式

引入微信jsdk 版本1.00 - 1.60都可以

在需要调用JS接口的页面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.6.0.js

如需进一步提升服务稳定性,当上述资源不可访问时,可改访问:http://res2.wx.qq.com/open/js/jweixin-1.6.0.js (支持https)。

备注:支持使用 AMD/CMD 标准模块加载方法加载

1、网页授权(静默授权、点击授权)

https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#0

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

scope 参数: 应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )

具体实现登录代码如下

// 判断openIdTime是否过期 过期失效12小时 let openIdTime = uni.getStorageSync("openIdTime"); if (openIdTime) { let nowTime = new Date().getTime(); if (nowTime - openIdTime > 43200000) { uni.clearStorageSync(); } } let urlParams = new URLSearchParams(window.location.search); let code = urlParams.get("code"); if (!code) { uni.setStorageSync("goto_url", window.location.href); } if (!code && !uni.getStorageSync("openId") && this.isAuthorization) { this.weChatLoginBtn(); } this.weixinCompelete(); 方法 // 登录 weChatLoginBtn() { if (!isWechat()) { uni.showToast({ title: "请在微信中打开", icon: "none", }); return; } this.$res.get(getWechatAppId).then((res) => { let appid = this.$res.fun(res); let baseUrl = encodeURIComponent(location.href); let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${baseUrl}&response_type=code&scope=snsapi_userinfo&state=null#wechat_redirect`; window.location.href = url; }); }, weixinCompelete() { let urlParams = new URLSearchParams(window.location.search); let code = urlParams.get("code"); let state = urlParams.get("state"); if (code) { getApp().showLoading(); // 记录此用户已授权 uni.setStorageSync("isAuthorization", true); console.log("登录吧"); this.$res .post(login, { code: code, }) .then((res) => { getApp().hideLoading(); if (res.data.status === 200) { let data = this.$res.fun(res); uni.setStorageSync("token", data.token); uni.setStorageSync("userInfo", data); uni.setStorageSync("openId", data.openId); // 设置openId过期时间 uni.setStorageSync("openIdTime", new Date().getTime()); let goto_url = uni.getStorageSync("goto_url"); // 切割goto_url获取参数 let urlParams = new URLSearchParams(goto_url.split("?")[1]); let params = {}; urlParams.forEach((value, key) => { params[key] = value; }); // 拼接参数 let url = ""; for (let key in params) { if (key !== "code" && key !== "state" && key !== "") { url += `${key}=${params[key]}&`; } } setTimeout(() => { uni.reLaunch({ url: `/pages/home/home?${url}`, }); }, 200); } else { let goto_url = uni.getStorageSync("goto_url"); // 切割goto_url获取参数 let urlParams = new URLSearchParams(goto_url.split("?")[1]); let params = {}; urlParams.forEach((value, key) => { params[key] = value; }); // 拼接参数 let url = ""; for (let key in params) { if (key !== "code" && key !== "state" && key !== "") { url += `${key}=${params[key]}&`; } } uni.reLaunch({ url: `/pages/home/home?${url}`, }); } }); return; } else { //已经登录 //直接走自己的下面接口 } },

2、背景音乐自动播放 / 分享给朋友、朋友圈、扫一扫

ios背景音乐播放,微信是不播放的,下面解决这个问题

//jwx.js export default { //判断是否在微信中 isWechat: function() { var ua = window.navigator.userAgent.toLowerCase(); if (ua.match(/micromessenger/i) == "micromessenger") { return true; } else { return false; } }, initJssdk: function(callback) { var uri = location.href.split("#")[0]; //获取当前url然后传递给后台获取授权和签名信息 uni.request({ url: xxx, //你的接口地址 method: "POST", data: { url: uri, }, success: (res) => { //返回需要的参数appId,timestamp,noncestr,signature等 //注入config权限配置 jWeixin.config({ debug: false, appId: res.data.data.appId, timestamp: res.data.data.timestamp, nonceStr: res.data.data.nonceStr, signature: res.data.data.signature, jsApiList: [ //这里是需要用到的接口名称 "onMenuShareAppMessage", //分享给朋友 "onMenuShareTimeline", //分享到朋友圈 "scanQRCode", //扫一扫接口 "chooseWXPay", //微信支付 "chooseImage", //拍照或从手机相册中选图接口 "previewImage", //预览图片接口 "uploadImage", //上传图片 "downloadImage", //下载图片 ], }); if (callback) { callback(res.data); } }, }); }, //在需要自定义分享的页面中调用 share: function(data, url) { url = url ? url : window.location.href; if (!this.isWechat()) { return; } //每次都需要重新初始化配置,才可以进行分享 this.initJssdk(function(signData) { jWeixin.ready(function() { var shareData = { title: data && data.title ? data.title : signData.site_name, desc: data && data.desc ? data.desc : signData.site_description, link: url, imgUrl: data && data.img ? data.img : signData.site_logo, success: function(res) { //用户点击分享后的回调,这里可以进行统计 }, cancel: function(res) {}, }; //分享给朋友接口 jWeixin.onMenuShareAppMessage(shareData); //分享到朋友圈接口 jWeixin.onMenuShareTimeline(shareData); }); }, url); }, // 微信扫一扫 scanQRCode: function(callBack) { if (!this.isWechat()) { //console.log('不是微信客户端') return; } //console.log(data); this.initJssdk(function(res) { jWeixin.ready(function() { console.log("微信扫一扫",res); jWeixin.scanQRCode({ needResult: 1, scanType: ["qrCode", "barCode"], success: function(res) { var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果 if (callBack) callBack(result); }, }); }); }); }, //在需要自定义分享的页面中调用 music: function(app, musicUrl, url) { url = url ? url : window.location.href; if (!this.isWechat()) { return; } //每次都需要重新初始化配置,才可以进行分享 this.initJssdk(function(signData) { jWeixin.ready(function() { let globalData = app.globalData; // 判断是否有背景音乐实例 if (globalData && globalData.audioCtx) { console.log("有背景音乐实例"); } else { // 背景音乐自动播放 createInnerAudioContext globalData.audioCtx = uni.createInnerAudioContext(); globalData.audioCtx.src = musicUrl; globalData.audioCtx.autoplay = true; globalData.audioCtx.loop = true; globalData.audioCtx.onPlay(() => { console.log("开始播放"); }); globalData.audioCtx.onError((res) => { console.log(res.errMsg); console.log(res.errCode); }); } }); }, url); }, };

页面具体调用

let shareData={ title:'分享标题', //其他参数自行查看 //link:'https://www.baidu.com'// //分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#111 } this.$jwx.share(shareData, 'https://www.baidu.com/home/home?id=123'); //调用音乐播放 需要传递app过去,那边保存到全局globalData里面 let app = getApp(); // 微信环境播放音乐 this.$jwx.music(app, '替换你的音乐播放地址'); //调取扫一扫 this.$jwx.scanQRCode((res) => { //res 扫描结果 }); //在任何页面停止音乐 playMusic() { this.audioCtx = getApp().globalData.audioCtx; if (this.audioCtx.paused) { this.audioCtx.play(); } else { this.audioCtx.pause(); } },

!!!敲黑板 微信扫一扫的页面进入方式。 ios进入扫一扫的单独网页,调用h5会发现调不起来,再次刷新页面又可以了。别急 进入页面方式改成这种,ok了,记得清空浏览器缓存,再试试

// 判断机型ios or android let system = uni.getSystemInfoSync().system; if (system.indexOf("iOS") > -1) { window.location.href = "https://baidu.com/pages/sao/sao"; } else { uni.navigateTo({ url: "/pages/sao/sao", }); }

总结几点坑: 1、本地开发必须要解决nginx代理,让你再微信开发者网页调试工具中访问域名,指定到你本地的项目进行开发。 2、uniapp 中 部分wx. 与微信浏览器中的有冲突。可以使用jWeixin来代替wx 3、ios进入扫一扫页面一定要按照上述方式 对你有帮助的话,点赞收藏吧!!!



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有