NFC 标签打开小程序

1,633 阅读1分钟

R-C.png

最近项目有个需要手机首页,根据nfc标签拉起微信直接打开小程序的需求,做做笔记

微信官方文档

准备工作

  1. 支持nfc功能的手机
  2. nfc标签卡贴
  3. 小程序申请设备能力

设备接入

小程序想要使用 NFC 标签打开小程序能力,首先需要接入设备

申请能力

设备接入审核通过后,在「小程序管理后台--功能--硬件设备--设备管理」页点击“申请设备能力”,选择“NFC 标签调起小程序”。

image.png

申请URL Scheme

通过微信服务端接口申请: developers.weixin.qq.com/miniprogram…

只有这个接口可以申请NFC拉起小程序的scheme

向nfc标签里写入 Record

要实现直接打开小程序,NFC 标签需要按照以下格式写入:

NFC 标签必须是 NFC Data Exchange Format (NDEF) 类型,标签中需要包含两条 Record :

  • URI Record

    • Type Name Format (TNF): 0x01 (Well-Known)
    • Type: U
    • Payload: 小程序 URL Scheme
  • Android Application Record, AAR

    • Type Name Format (TNF): 0x04 (NFC Forum external type)
    • Type: android.com:pkg
    • Payload: 微信安卓包名 com.tencent.mm

iOS 只识别 URI Record,安卓还需要 AAR 来指定拉起微信。

参考地址

写入两条Record

const records = [  {    id: str2ab('mini-ios'),    tnf: 1,    type: str2ab('U'),    payload: str2ab('小程序 URL Scheme', [0])
  },
  {
    id: str2ab('mini-android'),
    tnf: 4,
    type: str2ab('android.com:pkg'),
    payload: str2ab('com.tencent.mm')
  }
]      
/**
 * String to ArrayBuffer
 * @param {String} text 字符串
 * @param {String} extraBytes 额外的字节数组
 */
export function str2ab (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
}

也可直接使用下面的小程序

0.png

在里面写入上面接口获取到的scheme就可以了