微信小程序读写NFC标签(实现NFC标签快速拉起小程序)实战

背景:

复制代码
1、通过NFC进行写入,读取(读写NFC微信小程序只支持Andriod,ios可通过第三方工具写入或读取)
2、通过NFC标签贴近手机,自动拉起小程序某个页面(只要NFC标签里有urlScheme了,ios和Andriod都可以拉起)

前提:

复制代码
1、准备NFC标签,并且NFC标签支持读写操作
2、申请好NFC标签的能力,通过modelId从服务端获取urlScheme(申请NFC标签能力必须是企业的认证,申请比较麻烦,跟着官方提供的教程,一步一步来)
实例化NFC、开启读取NFC、监听NFC、写入内容到NFC
复制代码
  initNFC () {
    const __NFCInstance = wx.getNFCAdapter()
    this.setData({ NFCInstance: __NFCInstance })
    __NFCInstance.startDiscovery({
      success: (res) => {
        __NFCInstance.onDiscovered(this.discoverHandlerNfc)
      },
      fail: (err) => {
       	console.log(error)
      }
    })
  },

async discoverHandlerNfc (res) {
	// res:此res就是当前NFC标签里的内容,可根据转换自行取出里面需要用到的值
	const str = this.NFCbuf2hex(res.id)
	if (str ) {
		// 获取Ndef实例,通过Ndef读写
		const NDEF = await adapter.getNdef()
		// 建立连接
		NDEF.connect({
        	success: async (res) => {
        		// 写入records 兼容处理, 第一条ios,第二条Andriod
        		// urlScheme, 是通过小程序后台申请的设备能力后获得modeId,再通过modeId从服务端接口获取
          		const records = [
		            {
		              id: this.NFCStr2ab('mini-ios'),
		              tnf: 1,
		              type: this.NFCStr2ab('U'),
		              payload: this.NFCStr2ab('weixin://dl/xxxxxx/?t=xxxxxxxx', [0])
		            },
		            {
		              id: this.NFCStr2ab('mini-android'),
		              tnf: 4,
		              type: this.NFCStr2ab('android.com:pkg'),
		              payload: this.NFCStr2ab('com.tencent.mm')
		            }
		         ]
	             NDEF.writeNdefMessage({
	            	records: records,
		            success: (_res) => {
		              console.log('NDEF writeNdefMessage success -> ', _res)
		              // 写入成功 
		              // doSomething
		            },
		            fail: (_error) => {
		              console.log('NDEF writeNdefMessage _error -> ', _error)
		            }
	          	 })

       		 },
	         fail: (error) => {
	           console.log('NDEF error -> ', error)
	         }
          })

	}
	
},

// 把buffer转换为16进制字符串
NFCbuf2hex (arrayBuffer) {
  return Array.prototype.map.call(new Uint8Array(arrayBuffer), x => ('00' + x.toString(16)).slice(-2)).join('')
},

// 把要写入的内容转换为buffer格式
NFCStr2ab (text, extraBytes) {
  const uriStr = encodeURIComponent(text)
  const bytes = []
  for (let i = 0; i < uriStr.length; i++) {
    const code = uriStr.charAt(i)
    if (code === '%') {
      const hex = uriStr.slice(i + 1, i + 3)
      const hexVal = parseInt(hex, 16)
      bytes.push(hexVal)
      i += 2
    } else {
      bytes.push(code.charCodeAt(0))
    }
  }
  if (extraBytes) {
    bytes.unshift(...extraBytes)
  }
  return new Uint8Array(bytes).buffer
},

// 取消监听
handleCancelNFC () {
   this.data.NFCInstance.offDiscovered(this.discoverHandlerNfc)
},

完结!

相关推荐
恋猫de小郭14 分钟前
Flutter Zero 是什么?它的出现有什么意义?为什么你需要了解下?
android·前端·flutter
崔庆才丨静觅7 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60617 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了8 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅8 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅8 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅8 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment9 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅9 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊9 小时前
jwt介绍
前端