旗下品牌:
石家庄网站开发 石家庄网站开发公司

资讯动态

察而思、思而行、行而后语、知行合一

小程序NFC读取功能实现

发布时间:2025-12-12 热度:

我将为您创建一个完整的小程序页面,用于读取NFC标签内容。下面是我的实现思路和完整代码:

实现思路

  1. 创建简洁的UI界面,包含NFC状态显示和读取结果展示

  2. 实现NFC适配器初始化和状态检测

  3. 添加NFC标签读取和内容解析功能

  4. 提供错误处理和用户引导

完整代码实现

1. 页面结构 (index.wxml)

<!-- index.wxml -->
<view class="container">
  <!-- 标题区域 -->
  <view class="header">
    <text class="title">NFC读取工具</text>
    <text class="subtitle">轻触NFC标签以读取内容</text>
  </view>


  <!-- NFC状态显示 -->
  <view class="status-card {{nfcSupport ? 'supported' : 'unsupported'}}">
    <view class="status-header">
      <icon type="{{nfcSupport ? 'success_no_circle' : 'warn'}}" size="20"></icon>
      <text class="status-title">NFC支持状态</text>
    </view>
    <text class="status-text">
      {{nfcSupport ? '设备支持NFC功能' : '设备不支持NFC功能或未开启NFC'}}
    </text>
    <text class="status-text">当前状态: {{nfcState}}</text>
  </view>


  <!-- NFC读取按钮 -->
  <button 
    class="scan-btn" 
    bindtap="startScan" 
    disabled="{{!nfcSupport || isScanning}}"
    loading="{{isScanning}}"
  >
    {{isScanning ? '正在扫描...' : '开始扫描NFC标签'}}
  </button>


  <!-- 读取结果展示 -->
  <view class="result-card" wx:if="{{nfcData.techs && nfcData.techs.length > 0}}">
    <view class="result-header">
      <icon type="info" size="18"></icon>
      <text class="result-title">NFC标签信息</text>
    </view>
    
    <!-- 标签技术类型 -->
    <view class="result-section">
      <text class="section-title">标签技术类型:</text>
      <view class="tech-tags">
        <text class="tech-tag" wx:for="{{nfcData.techs}}" wx:key="index">{{item}}</text>
      </view>
    </view>


    <!-- NDEF消息内容 -->
    <view class="result-section" wx:if="{{nfcData.ndefMessages && nfcData.ndefMessages.length > 0}}">
      <text class="section-title">NDEF消息内容:</text>
      <scroll-view scroll-y class="ndef-scroll">
        <view class="ndef-message" wx:for="{{nfcData.ndefMessages}}" wx:key="index">
          <view class="ndef-item">
            <text class="ndef-field">类型: {{item.tnf}} ({{getTnfName(item.tnf)}})</text>
            <text class="ndef-field" wx:if="{{item.type}}">类型标识: {{arrayBufferToHex(item.type)}}</text>
            <text class="ndef-field" wx:if="{{item.id}}">ID: {{arrayBufferToHex(item.id)}}</text>
            <text class="ndef-field" wx:if="{{item.payload}}">负载数据: {{decodePayload(item.payload, item.tnf)}}</text>
          </view>
        </view>
      </scroll-view>
    </view>


    <!-- 原始ID -->
    <view class="result-section" wx:if="{{nfcData.id}}">
      <text class="section-title">标签ID:</text>
      <text class="id-text">{{arrayBufferToHex(nfcData.id)}}</text>
    </view>


    <!-- 时间戳 -->
    <view class="result-section">
      <text class="section-title">读取时间:</text>
      <text class="time-text">{{nfcData.timestamp}}</text>
    </view>
  </view>


  <!-- 使用说明 -->
  <view class="instruction-card">
    <view class="instruction-header">
      <icon type="help" size="18"></icon>
      <text class="instruction-title">使用说明</text>
    </view>
    <view class="instruction-content">
      <text class="instruction-item">1. 确保设备已开启NFC功能</text>
      <text class="instruction-item">2. 点击"开始扫描NFC标签"按钮</text>
      <text class="instruction-item">3. 将NFC标签靠近手机背面摄像头附近</text>
      <text class="instruction-item">4. 等待读取结果自动显示</text>
      <text class="instruction-item">5. 支持NDEF格式的NFC标签(如门禁卡、名片等)</text>
    </view>
  </view>


  <!-- 空状态提示 -->
  <view class="empty-tip" wx:if="{{!nfcData.techs || nfcData.techs.length === 0}}">
    <image src="/images/nfc-icon.png" class="empty-icon"></image>
    <text class="empty-text">暂无NFC读取记录</text>
    <text class="empty-subtext">请点击上方按钮开始扫描</text>
  </view>
</view>

2. 页面样式 (index.wxss)

/* index.wxss */
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}


/* 标题区域 */
.header {
  text-align: center;
  margin-bottom: 40rpx;
  padding: 20rpx;
}


.title {
  font-size: 44rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}


.subtitle {
  font-size: 28rpx;
  color: #666;
}


/* 状态卡片 */
.status-card {
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}


.status-card.supported {
  border-left: 8rpx solid #07c160;
}


.status-card.unsupported {
  border-left: 8rpx solid #fa5151;
}


.status-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}


.status-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-left: 15rpx;
  color: #333;
}


.status-text {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-top: 10rpx;
}


/* 扫描按钮 */
.scan-btn {
  background-color: #07c160;
  color: white;
  border-radius: 50rpx;
  font-size: 32rpx;
  height: 90rpx;
  line-height: 90rpx;
  margin: 40rpx 0;
  width: 100%;
}


.scan-btn[disabled] {
  background-color: #cccccc;
  color: #999;
}


/* 结果卡片 */
.result-card {
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  border-left: 8rpx solid #10aeff;
}


.result-header {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}


.result-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-left: 15rpx;
  color: #333;
}


/* 结果部分 */
.result-section {
  margin-bottom: 30rpx;
}


.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 15rpx;
}


/* 技术标签 */
.tech-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
}


.tech-tag {
  background-color: #e6f7ff;
  color: #10aeff;
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
  font-size: 26rpx;
}


/* NDEF消息区域 */
.ndef-scroll {
  max-height: 400rpx;
  background-color: #f9f9f9;
  border-radius: 12rpx;
  padding: 20rpx;
}


.ndef-message {
  margin-bottom: 25rpx;
  padding-bottom: 25rpx;
  border-bottom: 1rpx dashed #ddd;
}


.ndef-message:last-child {
  border-bottom: none;
}


.ndef-item {
  padding: 15rpx;
}


.ndef-field {
  display: block;
  font-size: 26rpx;
  color: #666;
  margin-bottom: 10rpx;
  word-break: break-all;
}


/* ID显示 */
.id-text, .time-text {
  display: block;
  background-color: #f9f9f9;
  padding: 20rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #333;
  word-break: break-all;
}


/* 使用说明 */
.instruction-card {
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}


.instruction-header {
  display: flex;
  align-items: center;
  margin-bottom: 25rpx;
}


.instruction-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-left: 15rpx;
  color: #333;
}


.instruction-content {
  padding-left: 15rpx;
}


.instruction-item {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 15rpx;
  line-height: 1.6;
}


.instruction-item:before {
  content: "• ";
  color: #10aeff;
  font-weight: bold;
}


/* 空状态提示 */
.empty-tip {
  text-align: center;
  padding: 60rpx 30rpx;
  background-color: white;
  border-radius: 16rpx;
  margin-top: 30rpx;
}


.empty-icon {
  width: 150rpx;
  height: 150rpx;
  opacity: 0.3;
  margin-bottom: 30rpx;
}


.empty-text {
  font-size: 32rpx;
  color: #999;
  display: block;
  margin-bottom: 15rpx;
}


.empty-subtext {
  font-size: 26rpx;
  color: #bbb;
}

3. 页面逻辑 (index.js)

// index.js
Page({
  data: {
    // NFC支持状态
    nfcSupport: false,
    nfcState: '未检测',
    
    // 扫描状态
    isScanning: false,
    
    // NFC数据
    nfcData: {
      techs: [],
      ndefMessages: [],
      id: null,
      timestamp: ''
    }
  },


  onLoad() {
    this.initNFC();
  },


  // 初始化NFC适配器
  initNFC() {
    // 检查是否支持NFC
    if (wx.getNFCAdapter) {
      const nfcAdapter = wx.getNFCAdapter();
      this.nfcAdapter = nfcAdapter;
      
      // 检查设备是否支持NFC
      nfcAdapter.startDiscovery({
        success: (res) => {
          console.log('NFC适配器初始化成功', res);
          this.setData({
            nfcSupport: true,
            nfcState: '已就绪,等待扫描'
          });
          
          // 停止发现,等待用户手动开始
          nfcAdapter.stopDiscovery();
        },
        fail: (err) => {
          console.error('NFC初始化失败', err);
          this.setData({
            nfcSupport: false,
            nfcState: '初始化失败:' + (err.errMsg || err)
          });
        }
      });
    } else {
      console.error('当前设备不支持NFC功能');
      this.setData({
        nfcSupport: false,
        nfcState: '设备不支持NFC功能'
      });
    }
  },


  // 开始扫描NFC标签
  startScan() {
    if (!this.nfcAdapter) {
      wx.showToast({
        title: 'NFC适配器未初始化',
        icon: 'error'
      });
      return;
    }


    this.setData({
      isScanning: true,
      nfcState: '扫描中...'
    });


    wx.showLoading({
      title: '请将NFC标签靠近手机',
      mask: true
    });


    // 开始发现NFC标签
    this.nfcAdapter.startDiscovery({
      success: (res) => {
        console.log('开始NFC发现成功', res);
        
        // 监听NFC标签
        this.nfcAdapter.onDiscovered(this.onNFCDiscovered);
        
        // 10秒后自动停止扫描
        setTimeout(() => {
          if (this.data.isScanning) {
            this.stopScan();
            wx.showToast({
              title: '扫描超时,未发现NFC标签',
              icon: 'none'
            });
          }
        }, 10000);
      },
      fail: (err) => {
        console.error('开始NFC发现失败', err);
        this.setData({
          isScanning: false,
          nfcState: '扫描失败'
        });
        wx.hideLoading();
        wx.showToast({
          title: '扫描失败',
          icon: 'error'
        });
      }
    });
  },


  // NFC标签发现回调
  onNFCDiscovered(res) {
    console.log('发现NFC标签', res);
    wx.hideLoading();
    
    const messages = res.messages || [];
    const techs = res.techs || [];
    const id = res.id || null;
    
    // 处理NDEF消息
    const ndefMessages = [];
    messages.forEach(msg => {
      if (msg.ndefMessage) {
        msg.ndefMessage.forEach(record => {
          ndefMessages.push({
            tnf: record.tnf,
            type: record.type,
            id: record.id,
            payload: record.payload
          });
        });
      }
    });
    
    // 更新数据
    this.setData({
      isScanning: false,
      nfcState: '读取成功',
      nfcData: {
        techs: techs,
        ndefMessages: ndefMessages,
        id: id,
        timestamp: this.formatTime(new Date())
      }
    });
    
    // 停止发现
    this.nfcAdapter.stopDiscovery();
    
    wx.showToast({
      title: 'NFC读取成功',
      icon: 'success',
      duration: 2000
    });
  },


  // 停止扫描
  stopScan() {
    if (this.nfcAdapter) {
      this.nfcAdapter.stopDiscovery();
      this.nfcAdapter.offDiscovered();
    }
    
    this.setData({
      isScanning: false,
      nfcState: '已停止'
    });
    
    wx.hideLoading();
  },


  // 工具方法:将ArrayBuffer转换为十六进制字符串
  arrayBufferToHex(buffer) {
    if (!buffer) return '';
    
    const hexArray = [];
    const uint8Array = new Uint8Array(buffer);
    
    for (let i = 0; i < uint8Array.length; i++) {
      const hex = uint8Array[i].toString(16).padStart(2, '0');
      hexArray.push(hex);
    }
    
    return hexArray.join(':').toUpperCase();
  },


  // 工具方法:解码NDEF负载数据
  decodePayload(payload, tnf) {
    if (!payload) return '';
    
    try {
      const uint8Array = new Uint8Array(payload);
      
      // 根据TNF类型选择解码方式
      switch (tnf) {
        case 1: // NFC Forum well-known type
          // 尝试解码为文本
          try {
            // 检查是否是文本类型 (根据NDEF规范,类型为'T')
            if (uint8Array.length > 0) {
              // 第一个字节是状态字节
              const statusByte = uint8Array[0];
              const encoding = (statusByte & 0x80) ? 'utf-16' : 'utf-8';
              const langCodeLength = statusByte & 0x3F;
              
              // 提取文本内容
              const textBytes = uint8Array.slice(1 + langCodeLength);
              
              if (encoding === 'utf-8') {
                return decodeURIComponent(escape(String.fromCharCode.apply(null, textBytes)));
              } else {
                // UTF-16解码简化处理
                return 'UTF-16编码文本';
              }
            }
          } catch (e) {
            console.log('文本解码失败,返回十六进制', e);
          }
          break;
          
        case 2: // Media-type (MIME)
          // 尝试解码为UTF-8文本
          try {
            return decodeURIComponent(escape(String.fromCharCode.apply(null, uint8Array)));
          } catch (e) {
            console.log('MIME解码失败,返回十六进制', e);
          }
          break;
          
        default:
          // 其他类型直接返回十六进制
          break;
      }
      
      // 默认返回十六进制字符串
      return this.arrayBufferToHex(payload);
      
    } catch (error) {
      console.error('解码负载数据失败', error);
      return '解码失败';
    }
  },


  // 工具方法:获取TNF类型名称
  getTnfName(tnf) {
    const tnfNames = {
      0: 'Empty',
      1: 'NFC Forum Well-Known Type',
      2: 'Media-type',
      3: 'Absolute URI',
      4: 'NFC Forum External Type',
      5: 'Unknown',
      6: 'Unchanged',
      7: 'Reserved'
    };
    return tnfNames[tnf] || 'Unknown TNF';
  },


  // 工具方法:格式化时间
  formatTime(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hour = date.getHours().toString().padStart(2, '0');
    const minute = date.getMinutes().toString().padStart(2, '0');
    const second = date.getSeconds().toString().padStart(2, '0');
    
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  },


  onUnload() {
    // 页面卸载时停止扫描
    this.stopScan();
  }
});

4. 页面配置文件 (index.json)

{
  "usingComponents": {},
  "navigationBarTitleText": "NFC读取工具",
  "navigationBarBackgroundColor": "#07c160",
  "navigationBarTextStyle": "white"
}

使用说明

1. 配置小程序权限

在小程序项目的 app.json 中添加以下配置:

{
  "requiredPrivateInfos": [
    "getNFCAdapter"
  ]
}

2. 创建图标文件

在项目根目录创建 images 文件夹,并添加一个 nfc-icon.png 图标文件(用于空状态显示)。

3. 功能特点

  • NFC支持检测:自动检测设备是否支持NFC

  • 标签技术识别:显示NFC标签支持的技术类型

  • NDEF消息解析:解析标准NDEF格式的NFC数据

  • 数据格式化:十六进制显示和文本解码

  • 错误处理:完善的错误提示和用户引导

  • 用户体验:简洁直观的界面设计

4. 注意事项

  1. NFC功能仅支持部分安卓设备

  2. 需要用户手动开启手机的NFC功能

  3. 某些NFC标签可能需要特定格式才能读取

  4. 小程序NFC API目前主要支持NDEF格式的NFC标签

5. 测试建议

  1. 使用支持NFC的安卓手机进行测试

  2. 准备常见的NFC标签(如门禁卡、公交卡等)

  3. 确保手机已开启NFC功能

  4. 将NFC标签靠近手机背面摄像头区域

这个实现提供了一个完整的NFC读取小程序页面,具有美观的UI和完整的错误处理机制。您可以根据实际需求进一步扩展功能,如添加NFC写入功能、历史记录保存等。

 

 

 

 

 

下一篇:没有了

联系尚武科技
客户服务
石家庄APP开发
400-666-4864
为您提供售前购买咨询、解决方案推荐等1V1服务!
技术支持及售后
石家庄APP开发公司
0311-66682288
为您提供从产品到服务的全面技术支持 !
客户服务
石家庄小程序开发
石家庄小程序开发公司
加我企业微信
为您提供售前购买咨询、
解决方案推荐等1V1服务!
石家庄网站建设公司
咨询相关问题或预约面谈,可以通过以下方式与我们联系。
石家庄网站制作
在线联系:
石家庄Web开发
石家庄软件开发
石家庄软件开发公司
ADD/地址:
河北·石家庄
新华区西三庄大街86号河北互联网大厦B座二层
Copyright © 2008-2025尚武科技 保留所有权利。 冀ICP备12011207号-2 石家庄网站开发冀公网安备 13010502001294号《互联网平台公约协议》
Copyright © 2025 www.sw-tech.cn, Inc. All rights reserved