微信小程序nfc读取M1卡数据

   如果没看过我另一篇nfc读卡数据的可以去看一下,里面有一些描述可以帮助到大家。

刚通过测试代码还没有优化,有什么问题大家也可以提出来。

本次是nfc读取m1卡数据的,m1卡数据是有密钥分扇区的所以大家一定要问清楚写入卡数据的同学他吧数据写入到了那个扇区以及提供卡的第三方密钥也要问清楚,哪怕错了一个字节都会影响。

 nfcRead() {

        var that = this;

        const adapter = wx.getNFCAdapter();

        console.log("获取NFC实例", adapter)

        adapter.onDiscovered(res => {

            console.log("读取到卡片了", res);

            let tagId = res.id;

            console.log("获取到tagID:", tagId);

            if (res.techs.includes(adapter.tech.mifareClassic)) { //如果影响你nfc可以去掉

                console.log('发现' + adapter.tech.mifareClassic + '卡');

                let mifareClassic = adapter.getMifareClassic();

                mifareClassic.connect({

                    success: res => {

                        console.log("设备已连接", res)

                        console.log("开始拼接验密指令。。。");

                        

 

                        var arr = [0x60, 0x04, 0x11, 0x22, 0x33, 0x44, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF];

                        var arrayBuffer = new Uint8Array(arr).buffer

                        console.log("解密指令为:", arrayBuffer);

                        mifareClassic.transceive({

                            data: arrayBuffer,

                            success: function (res) {

                                console.log('发送数据并解密成功, 接收数据如下:', res);

                            },

                            fail: function (err) {

                                console.log('发送数据失败A', err);

                                wx.showToast({

                                    title: 'nfc失败!',

                                    icon:'error'

                                })

                            }

                        })

                    }

                })

                mifareClassic.isConnected({

                    success: function (isConnected) {

                        console.log('成功连接', isConnected);

                        var arr01 = [0x30, 0x04];

                        var arrayBuffer01 = new Uint8Array(arr01).buffer

                        console.log('arrayBuffer02',arrayBuffer01);

                        var strList = {

                            orgId: '',

                            orgUserId: ''

                        }

                        mifareClassic.transceive({

                            data: arrayBuffer01,

                            success: function (res) {

                                console.log('读取数据:', res);

                                wx.showLoading({

                                  title: '识别中...',

                                  mask: true,

                                  success: (res) => {},

                                  fail: (res) => {},

                                  complete: (res) => {},

                                })

                                const arrayBuffer = res.data    // 获取通讯数据,类型为ArrayBuffer

                                const data16 = that.buf2hex(arrayBuffer)    // ArrayBuffer转16进制

                                const requestData = that.hexToStr(data16) // 16进制转字符串

                                let arr = requestData.split('')

                                let str = ''

                                arr.forEach((item,index)=>{

                                    console.log(item,item.length);

                                    if(item>=0){

                                        str += item

                                    }

                                })

                                strList.orgId = str

                                console.log('requestData',str,'arr',arr)

                            },

                            fail: function (err) {

                                console.log('失败', err);

                                wx.showToast({

                                    title: 'nfc失败!',

                                    icon:'error'

                                  })

                            }

                        })

                        var arr02 = [0x30, 0x05];

                        var arrayBuffer02 = new Uint8Array(arr02).buffer

                        console.log('arrayBuffer02',arrayBuffer02);

                        mifareClassic.transceive({

                            data: arrayBuffer02,

                            success: function (res) {

                                console.log('读取数据:', res);

                                wx.showLoading({

                                  title: '识别中...',

                                  mask: true,

                                  success: (res) => {},

                                  fail: (res) => {},

                                  complete: (res) => {},

                                })

                                const arrayBuffer = res.data    // 获取通讯数据,类型为ArrayBuffer

                                const data16 = that.buf2hex(arrayBuffer)    // ArrayBuffer转16进制

                                const requestData = that.hexToStr(data16) // 16进制转字符串

                                let arr = requestData.split('')

                                let str = ''

                                arr.forEach((item,index)=>{

                                    console.log(item,item.length);

                                    if(item>=0){

                                        str += item

                                    }

                                })

                                strList.orgUserId = str

                                console.log('requestData2',strList)

                                that.getNfcCardList(strList)

                            },

                            fail: function (err) {

                                console.log('失败', err);

                                wx.showToast({

                                    title: 'nfc失败!',

                                    icon:'error'

                                  })

                            }

                        })

                    }

                });

            } else {

                console.log('没发现卡');

                wx.showToast({

                  title: '卡片类型有误!',

                  icon:'error'

                })

            }

        })

        adapter.startDiscovery({

            success: function (res) {

                console.log('startDiscovery:', res);

            },

            fail(err) {

                console.log('failed to discover:', err)

                if(!err.errCode){

                    wx.showToast({

                      title: '请检查NFC功能是否正常!',

                      icon: 'none'

                    })

                    return

                  }

                  switch (err.errCode) {

                    case 13000:

                      wx.showToast({

                        title: '设备不支持NFC!',

                        icon: 'none'

                      })

                      break;

                    case 13001:

                      wx.showToast({

                        title: '系统NFC开关未打开!',

                        icon: 'none'

                      })

                      break;

                    case 13019:

                      wx.showToast({

                        title: '用户未授权!',

                        icon: 'none'

                      })

                      break;

                    case 13010:

                      wx.showToast({

                        title: '未知错误!',

                        icon: 'none'

                      })

                      break;

                  }

            }

        })

       

    },

    buf2hex(arrayBuffer) {

        return Array.prototype.map.call(new Uint8Array(arrayBuffer), x => ('00' + x.toString(16)).slice(-2)).join('');

    },

    hexToStr(hex) {

        // 去掉字符串首尾空格

        let trimedStr = hex.trim()

        // 判断trimedStr前两个字符是否为0x,如果是则截取从第三个字符及后面所有,否则返回全部字符

        let rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr

        // 得到rawStr的长度

        let len = rawStr.length

        // 如果长度不能被2整除,那么传入的十六进制值有误,返回空字符

        if (len % 2 !== 0) {

            return ""

        }

        let curCharCode // 接收每次循环得到的字符

        let resultStr = [] // 存转换后的十进制值数组

        for (let i = 0; i < len; i = i + 2) {

            curCharCode = parseInt(rawStr.substr(i, 2), 16)

            resultStr.push(curCharCode)

        }

        // encoding为空时默认为utf-8

        let bytesView = new Uint8Array(resultStr) // 8 位无符号整数值的类型化数组

        // TextEncoder和TextDecoder对字符串和字节流互转  

        // let str = new TextDecoder(encoding).decode(bytesView)因为小程序中没有TextDecoder,经查阅资料,下载https://github.com/inexorabletash/text-encoding并const encoding = require("./text-encoding-master/lib/encoding.js")引入后使用下面方式即可:

        let str = new encoding.TextDecoder("gbk").decode(bytesView)

        return str

    },

这里大家写完后解数据encoding这个方法会报错,大家可以去链接下载对应文件引入一下,如果解出来的数据不理想,只能再去找下你要的数据方法了。

https://github.com/inexorabletash/text-encoding ,下载文件 encoding.js 和 encoding-indexes.js。

import encoding from '@/xxx/encoding.js' // 引入js

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
微信小程序支持NFC(Near Field Communication)的读写功能,可以通过对NFC标签的读取和写入实现与设备的交互。在微信小程序中,可以通过wx.startHCE()方法启动HCE服务,使手机模拟一个NFC片。可以通过wx.onHCEMessage()方法监听HCE服务接收到的消息,并通过wx.sendHCEMessage()方法发送消息。这样,可以实现小程序与其他NFC设备之间的通信。 要使用NFC读写功能,首先需要在小程序的app.json文件中声明NFC权限。例如,在"permission"字段中添加"nfc"权限。然后,在小程序的页面中,使用wx.startHCE()方法来启动HCE服务。在启动HCE服务之后,可以监听HCE服务接收到的消息,并处理这些消息。可以使用wx.onHCEMessage()方法来监听HCE服务接收到的消息,并在回调函数中处理这些消息。同时,可以使用wx.sendHCEMessage()方法来向HCE服务发送消息。 需要注意的是,NFC读写功能在不同的手机上的支持程度可能会有所差异。在使用NFC读写功能时,建议进行兼容性测试,并提供适当的错误处理机制,以确保用户的良好体验。 总结起来,要在微信小程序中实现NFC的读写功能,需要进行以下步骤: 1. 在app.json文件中声明NFC权限。 2. 使用wx.startHCE()方法启动HCE服务。 3. 使用wx.onHCEMessage()方法监听HCE服务接收到的消息,并进行处理。 4. 使用wx.sendHCEMessage()方法向HCE服务发送消息。 希望以上信息对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值