最新文章
小程序NFC读取功能实现
发布时间:2025-12-12
热度:
<!-- 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>/* 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;
}// 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();
}
});{
"usingComponents": {},
"navigationBarTitleText": "NFC读取工具",
"navigationBarBackgroundColor": "#07c160",
"navigationBarTextStyle": "white"
}app.json
{
"requiredPrivateInfos": [
"getNFCAdapter"
]
}imagesnfc-icon.png












冀公网安备