微信小程序实现微信APP上的扫一扫扫码跳到小程序对应的结果页面和签字等功能
最近做了一個小程序項目,這個小程序是搭配APP端使用的,大概需求是這樣的,用戶用微信的掃一掃或小程序首頁的掃一掃都可以實現對APP上的二維碼進行掃碼識別,識別成功之后跳到頁面進行渲染,然后用戶可以對其簽字和編輯提交等。這個小程序前端方面主要的技術難點有根據后端返回的接口數據生成動態的表單、簽字功能、獲取用戶微信頭像昵稱并檢測是否重復授權、微信APP上的掃一掃掃碼跳到小程序對應的結果頁面上去。
小程序首頁:
這里要注意的是,我們要獲取微信用戶的頭像、昵稱、手機號,而頭像、昵稱作為一步,第一次授權,獲取授權號作為第二步,第二次授權,然后我們通過調接口來知道是否已經授過權:
當用戶掃碼成功后會跳到一個臨時頁面temporary.wxml,這個頁面作為一個中轉頁面,主要是為了當用戶從微信的掃一掃進來時也是先進這個中轉頁面再到結果頁面,相當于從微信的掃一掃進來時不用到小程序的掃一掃里再授權什么的。這里我在js的onLoad里做了區分, 通過decodeURIComponent( )來獲取二維碼原始內容,代碼如下:
//temporary.wxml <view class="temporary"> </view>//temporary.js // pages/temporary/temporary.js import api from '../../utils/api.js'; Page({/*** 頁面的初始數據*/data: {},/*** 生命周期函數--監聽頁面加載*/onLoad(query) {console.log("接收", query)wx.showLoading({title: '加載中',})let string;if (query.hasOwnProperty('result')) {//從小程序內的掃一掃跳轉過來的string = decodeURIComponent(query.result)console.log("sadas", decodeURIComponent(query.result))} else if (query.hasOwnProperty('q')) {//從微信掃一掃跳轉過來的string = decodeURIComponent(query.q) //獲取到二維碼原始鏈接內容console.log("外面微信掃碼獲得的", string)// const scancode_time = parseInt(query.scancode_time) // 獲取用戶掃碼時間 UNIX 時間戳}// console.log("route", this.getQueryVariable(string, "route"))// console.log("tkId", this.getQueryVariable(string, "tkId"))// console.log("batchNo", this.getQueryVariable(string, "batchNo"))// console.log("randomCode", this.getQueryVariable(string, "randomCode"))// console.log("formId", this.getQueryVariable(string, "formId"))try {var val = wx.getStorageSync('openid')let route = this.getQueryVariable(string, "route")let params = {route: route,tkId: this.getQueryVariable(string, "tkId"),batchNo: this.getQueryVariable(string, "batchNo"),randomCode: this.getQueryVariable(string, "randomCode"),formId: this.getQueryVariable(string, "formId") ? this.getQueryVariable(string, "formId") :''}if (val) {// 本地有openidparams.openId = vallet that = this//檢測用戶之前是否授權過api.getSetting({"openId": val}).then(res => {console.log("檢測是否授權過", res.data)wx.hideLoading()if (res.data.code == 0) {if (res.data.result) {//授權過api.getCodeContent(params).then(res => {console.log("二維碼業務內容成功獲取", res)if (res.data.code == 1) {//二維碼失效wx.showModal({content: `${res.data.message}`,showCancel: false,confirmText: '我知道了',success(res) {if (res.confirm) {// console.log('用戶點擊確定')that.goHome()} else if (res.cancel) {// console.log('用戶點擊取消授權')}}})} else if (res.data.code == 0) {if (route == 'activeTask') {//激活任務let myParams = {...params,}if (myParams.hasOwnProperty('formId')) {delete myParams.formId}api.saveScanResult(myParams).then(response => {console.log("激活", response)if(response.data.code == 0){wx.showModal({title: '提示',content: `${response.data.result}`,showCancel: false,confirmText: '我知道了'}).then(res => {that.goHome()}).catch(err => {})}else{wx.showModal({title: '提示',content: `${response.data.message}`,showCancel: false,confirmText: '我知道了'}).then(res => {that.goHome()}).catch(err => {})}}).catch(error => {wx.showModal({title: '服務器內部出錯',content: '請稍后重試',showCancel: false,confirmText: '我知道了'})})} else if (route == 'submitForm') {//表單提交// formType為1新表單 通用表單 if (res.data.result.formType == 1) {wx.navigateTo({url: '/pages/check/check_detail'})wx.setStorageSync('FormDetailTitle',res.data.result.title)//將場所登記表緩存在本地wx.setStorageSync('placeFormJson', res.data.result.formJson)wx.setStorageSync('taskItemResultId', JSON.stringify(res.data.result.taskItemResultId))//將從業人員列表緩存到本地wx.setStorageSync('personFormJson', JSON.stringify(res.data.result.personFormJson))} else if (res.data.result.formType == 3) {//formType為3舊表單 自定義表單wx.navigateTo({url: '/pages/check/check_detail_old'})wx.setStorageSync('oldFormDetailTitle',res.data.result.title)wx.setStorageSync('oldFormJson',res.data.result.formJson)wx.setStorageSync('taskItemResultId', JSON.stringify(res.data.result.taskItemResultId))wx.setStorageSync('oldResultId',JSON.stringify(res.data.result.taskItemResultId))}wx.setStorageSync('params', JSON.stringify(params))wx.setStorageSync('taskItemId', res.data.result.taskItemId)//通過isFill判斷表單是否填寫過 isFill為0是未填寫wx.setStorageSync('isFill', JSON.stringify(res.data.result.isFill))}} else if (res.data.code == 401) {wx.showModal({title: '服務器內部出錯',showCancel: false,content: '請稍后重試',confirmText: '我知道了'})}}).catch(err => {console.log("二維碼業務內容獲取失敗", err)})} else {wx.hideLoading()//沒授權過就提醒其授權that.isAuthorize()}}})} else {//本地拿不到openId 提醒需要授權that.isAuthorize()}} catch (e) {}},//提醒用戶授權isAuthorize() {let that = this;wx.showModal({content: '您還沒有授權',showCancel: false,confirmText: '我知道了',success(res) {if (res.confirm) {// console.log('用戶點擊確定')that.goHome()} else if (res.cancel) {// console.log('用戶點擊取消授權')}}})},//跳回首頁goHome() {wx.hideLoading()wx.showLoading({title: '正在跳回首頁...'})//跳回首頁setTimeout(() => {wx.redirectTo({url: '/pages/index/index',success: function() {},fail: function() {},complete: function() {wx.hideLoading()}})}, 2000)},//獲取url參數的方法getQueryVariable(url, variable){var query = url.substr(url.indexOf('?') + 1);// console.log("query",query)var vars = query.split("&");for (var i = 0; i < vars.length; i++) {var pair = vars[i].split("=");if (pair[0] == variable) {return pair[1];}}return (false);},/*** 生命周期函數--監聽頁面初次渲染完成*/onReady() {},/*** 生命周期函數--監聽頁面顯示*/onShow() {},/*** 生命周期函數--監聽頁面隱藏*/onHide() {},/*** 生命周期函數--監聽頁面卸載*/onUnload() {wx.hideLoading()},/*** 頁面相關事件處理函數--監聽用戶下拉動作*/onPullDownRefresh() {},/*** 頁面上拉觸底事件的處理函數*/onReachBottom() {},/*** 用戶點擊右上角分享*/onShareAppMessage() {} })我們寫完這些邏輯還不夠,要實現微信APP上的掃一掃掃碼跳到小程序上的某個頁面,我們還需要在微信公眾平臺后臺進行配置,找到后臺的開發管理–開發設置–掃普通鏈接二維碼打開小程序:
我們線上環境是8443端口,然后我們對其配置如下:
然后我們的app.json里pages頁面第一個依然是pages/index/index,而我們在提交代碼審核的頁面修改路徑一定要改為pages/temporary/temporary,這樣就能保證我們用戶如果是正常搜索進小程序來是首頁index.wxml,如果是用微信的掃一掃進小程序就是臨時頁temporary.wxml
小程序簽字頁面主要用到了canvas,然后頁面上有重新簽名和完成兩個按鈕:
//sign.wxml <canvas canvas-id="firstCanvas" id='firstCanvas' bindtouchstart="bindtouchstart" bindtouchmove="bindtouchmove"></canvas><view class="bottomBox"><view class="clear" bindtap='clear'>重新簽名</view><view class="save {{sureBtn?'sureBet':''}}" bindtap='export'>完成</view> </view>//sign.js //index.js //獲取應用實例 const app = getApp()Page({data: {context: null,index: 0,height: 0,width: 0,writeTips: '請清晰書寫您的簽名',writeTipsTrue: true,src: '',src1: '',sureBtn: false,saveContext: null,pixelRatio:2 //設備像素比默認為2},/**記錄開始點 */bindtouchstart: function(e) {let {writeTipsTrue} = this.dataif (writeTipsTrue) {this.data.context.clearRect(0, 0, this.data.width, this.data.height)this.setData({writeTipsTrue: false,sureBtn: true})}this.data.context.moveTo(e.changedTouches[0].x, e.changedTouches[0].y)},/**記錄移動點,刷新繪制 */bindtouchmove: function(e) {this.data.context.setLineWidth(2) // 設置線條寬度this.data.context.lineTo(e.changedTouches[0].x, e.changedTouches[0].y)this.data.context.stroke()this.data.context.draw(true)this.data.context.moveTo(e.changedTouches[0].x, e.changedTouches[0].y)},/**清空畫布 */clear() {let context = this.data.contextthis.setData({writeTipsTrue: true,sureBtn: false})context.clearRect(0, 0, this.data.width, this.data.height)// this.data.saveContext.clearRect(0, 0, this.data.height, this.data.width);context.save()// context.setTransform(1, 0, 0, 1, Math.ceil(this.data.width / 2), 155) // 旋轉畫布 默認文字區域context.setTransform(1, 0, 0, 1, 50, 50)let str = this.data.writeTipscontext.setFontSize(24)context.setFillStyle('#ADADB2')context.fillText(str, 0, 0)context.restore()context.draw()},/**導出圖片 */export () {const that = thisif (!that.data.sureBtn) {wx.showModal({title: '您沒有簽名',content: '請簽完名后再提交',showCancel: false,confirmText: '我知道了'})return false}let signImgwx.canvasToTempFilePath({x: 0,y: 0,width: that.data.width,height: that.data.height,destWidth: that.data.width * that.data.pixelRatio,destHeight: that.data.height * that.data.pixelRatio,canvasId: 'firstCanvas',success(res) {signImg = res.tempFilePaththat.setData({src1: signImg})//下載圖片wx.getImageInfo({src: signImg, // 簽字畫布生成的暫存地址success(res) {let rototalImg = res.paththat.setData({src: rototalImg})if (rototalImg) {// 單獨處理圖片旋轉that.saveImg(rototalImg)}},fail(err) {}})},})},// drew imgsaveImg(signImg) {// 旋轉圖let that = thislet context = wx.createCanvasContext('firstCanvas');that.setData({saveContext: context})context.setTransform(1, 0, 0, 1, 50, 50)//繪制圖片 生成圖片函數寫在draw()的回調中,不然會出現還沒有畫圖就生成圖片的問題context.draw(true, function() {wx.canvasToTempFilePath({x: 0,y: 0,width: that.data.width,height: that.data.height,destWidth: that.data.width * that.data.pixelRatio,destHeight: that.data.height * that.data.pixelRatio,canvasId: 'firstCanvas',fileType: 'png',success: function(res) {var tempFilePath = res.tempFilePath//將圖片轉成base64格式wx.getFileSystemManager().readFile({filePath:tempFilePath,encoding: 'base64',success: res => {var userImageBase64 ='data:image/jpg;base64,' + res.data;// console.log("簽字base64",// userImageBase64);// 生成圖片 并返回上一頁 賦值var curPages = getCurrentPages()var currPage = curPages[curPages.length - 1]; //當前頁面var prevPage = curPages[curPages.length - 2] //上一頁面prevPage.setData({sign: userImageBase64})wx.navigateBack({delta: 1,})}})},fail: function(res) {// console.log(res)},})})},onShow: function() {// 進入頁面渲染canvaslet query = wx.createSelectorQuery()const that = thislet contextquery.select('#firstCanvas').boundingClientRect()query.exec(function(rect) {let width = rect[0].widthlet height = rect[0].heightthat.setData({width,height,})const context = wx.createCanvasContext('firstCanvas')that.setData({context: context,})context.save()// context.translate(Math.ceil(width / 2) - 20,0)context.setTransform(1, 0, 0, 1, 50, 50)let str = that.data.writeTipscontext.setFontSize(24)context.setFillStyle('#ADADB2')context.fillText(str, 0, 0)context.restore()context.draw()})},onLoad(){//獲取設備像素比wx.getSystemInfo({success: (res) => {// console.log("獲取設備像素比",res)this.setData({pixelRatio : res.pixelRatio})}})},// 彈窗onToast() {app.toast(this, {type: 'text',text: '生成成功',})},onShareAppMessage: (res) => {} })//sign.wxss /* pages/sign/sign.wxss */#firstCanvas{width:95vw;height:78vh;margin:0 auto;border:1rpx solid #ACACAC;}#saveImg{width:95vw;border:1px solid blue; }.bottomBox{display: flex; margin-top:10rpx;justify-content: center;}.clear{width: 157rpx;text-align: center;height: 44rpx;line-height: 44rpx;border-radius: 22rpx ;opacity: 1;border: 1rpx solid #ACACAC;font-size: 15rpx;font-family: PingFang SC-Bold, PingFang SC;font-weight: bold;color: #EC3535;margin-right:20rpx; }.save{width: 157rpx;height: 44rpx;line-height: 44rpx;border-radius: 22rpx ;text-align: center;font-size: 15rpx;font-family: PingFang SC-Bold, PingFang SC;font-weight: bold;color: #FFFFFF;background: linear-gradient(270deg, #3670FF 0%, #65A7FF 100%);opacity: 1; }.sureBet{}//sign.json {"usingComponents": {},"navigationBarTitleText":"簽名","pageOrientation":"landscape","disableScroll":true }總結
以上是生活随笔為你收集整理的微信小程序实现微信APP上的扫一扫扫码跳到小程序对应的结果页面和签字等功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 西安财经大学“荣耀杯”迷你马拉松——微博
- 下一篇: 高斯滤波的理解与学习