微信小程序上传身份证(身份证识别)

1、父页面引用组件

<view class="topic_box">
  <view>请拍摄本人真实有效的身份证原件和人脸照片</view>
  <view>拍摄时请保证身份证边缘完整,内容清晰可见</view>
</view>

<view class="upload_box" data-type="idCardPortrait" bind:tap="onChooseImg">
  <image class="upload_img" mode="aspectFit" src="{{info.idcardPortraitPath ? info.idcardPortraitUrl : '../../imgs/upload_icon/1.png'}}"></image>
</view>

<view wx:if="{{info.idcardPortraitPath}}" class="upload_desc-box">
  <view class="upload_desc">
    <view class="desc_ft">姓名</view>
    <view class="desc_bd">{{info.name}}</view>
  </view>
  <view class="upload_desc">
    <view class="desc_ft">身份证号</view>
    <view class="desc_bd">{{info.id}}</view>
  </view>
</view>

<view class="upload_box" data-type="idCardEmblem" bind:tap="onChooseImg">
  <image class="upload_img" mode="aspectFit" src="{{info.idcardEmblemPath ? info.idcardEmblemUrl : '../../imgs/upload_icon/3.png'}}"></image>
</view>

<view wx:if="{{info.idcardEmblemPath}}" class="upload_desc-box">
  <view class="upload_desc">
    <view class="desc_ft">签发机关</view>
    <view class="desc_bd">{{info.authority}}</view>
  </view>
  <view class="upload_desc">
    <view class="desc_ft">有效期</view>
    <view class="desc_bd">{{validDate}}</view>
  </view>
</view>

<!--<view class="upload_box" data-type="portrait" bind:tap="onChooseImg">
  <image class="upload_img" mode="aspectFit" src="{{info.portraitPath ? info.portraitUrl : '../../imgs/upload_icon/2.png'}}"></image>
</view>-->

<view hidden="{{takeVisible}}" class="footer_box">
  <view class="primary_btn" bind:tap="onSaveInfo">确定提交</view>
</view>


<real-name visible="{{takeVisible}}" take-type="{{takeType}}" bind:close="onCloseCamera"></real-name>
import dayjs from 'dayjs';

import wxOcrService, {WxOcr} from "../../../services/wxOcr";
import userInfoService from "../../../services/userInfo";
import { convertValidDate,validateIdCard } from "../../../utils/tools";
import {showToast} from "../../../utils/project";



// 获取应用实例
const app = getApp<IAppOption>()

interface TakeResult {
  type: string;
  tempFilePath: string;
}

interface ChooseImgDataSet {
  type: string;
}

interface DataType {
  info: WxOcr.IdCard.Result;
  validDate: string;
  takeVisible: boolean;
  takeType: string;
}

interface CustomOption extends PageInitCustomOption {
  routerType?: string;
  leaseId?: number;
  onChooseImg: (ev: TapBaseEvent<ChooseImgDataSet>) => void;
  handleOcrImg: (file: string, type: string) => void;
  onCloseCamera: (ev: WechatMiniprogram.CustomEvent<TakeResult>) => void;
  onSaveInfo: Function;
}

Page<DataType, CustomOption>({
  data: {
    info: {
      addr: '',
      authority: '',
      idcardEmblemPath: '',
      idcardEmblemUrl: '',
      idcardPortraitPath: '',
      idcardPortraitUrl: '',
      portraitPath: '',
      portraitUrl: '',
      birth: '',
      gender: '',
      id: '',
      name: '',
      nationality: '',
      validDate: '',
      valid_date: '',

    },
    validDate: '',
    takeVisible: false,
    takeType: 'back',
  },
  async onLoad(options) {
    if (options.type) {
      this.routerType = options.type;
    }
    if (options.leaseId) {
      this.leaseId = Number(options.leaseId);
    }
    const obj = await app.waitLogin();
    this.handleInit(obj);
  },
  // 是否注册用户
  handleInit(obj) {
    console.log(obj.token);
  },

  // 处理图片
  async handleOcrImg (file, type) {
    console.log('handleOcrImg===',file, type)
    const imgObj = await app.uploadFile(file, 10);
   console.log('imgObj===',imgObj)
    if (!imgObj) return;

    const {
      info,
    } = this.data;

    if (type === 'portrait') {
      wx.hideLoading().then();

      this.setData({
        info: {
          ...info,
          portraitUrl: file,
          portraitPath: imgObj.path,
        },
      });
      return;
    }

    wx.showLoading({ title: '识别中', mask: true }).then();
    const [err, res] = await wxOcrService.idCard({ path: imgObj.path });
    console.log('wxOcrService.res==',res)
    console.log('wxOcrService.err==',err)
    if (err) {
      wx.hideLoading().then();
      showToast(err);
      return;
    }
    if (!res) return;

    if (type === 'idCardEmblem') {
      const validDate = convertValidDate(res.validDate || res.valid_date);

      this.setData({
        validDate: `${validDate.startDate} 至 ${validDate.endDate}`,
        info: {
          ...info,
          idcardEmblemPath: res.idcardEmblemPath,
          idcardEmblemUrl: res.idcardEmblemUrl,
          authority: res.authority,
          validDate: res.validDate || res.valid_date,
        },
      });
    } else if (type === 'idCardPortrait') {
      this.setData({
        info: {
          ...info,
          idcardPortraitPath: res.idcardPortraitPath,
          idcardPortraitUrl: res.idcardPortraitUrl,
          name: res.name,
          id: res.id,
          birth: res.birth,
          addr: res.addr,
          gender: res.gender,
          nationality: res.nationality,
        },
      });
    }

    wx.hideLoading().then();

  },

  // 拍摄图片
  onChooseImg(ev) {
    console.log('onChooseImg===',ev)
    this.setData({
      takeVisible: true,
      takeType: ev.currentTarget.dataset.type,
    });

    /* wx.chooseImage({
       count: 1,
       sizeType: ['original'],
       sourceType: ['camera'],
       success(obj) {

         that.handleOcrImg(obj.tempFilePaths[0], type);

       },
     });*/
  },

  onCloseCamera(ev) {
    console.log('onCloseCamera===',ev)
    if (ev.detail) {
      this.handleOcrImg(ev.detail.tempFilePath, ev.detail.type);
    }
    this.setData({
      takeVisible: false,
      takeType: '',
    });
  },

  // 保存用户信息
  async onSaveInfo() {
    const {
      info,
    } = this.data;

    if (info.idcardEmblemPath && info.idcardPortraitPath && info.id
      && info.name && info.gender && info.nationality && info.birth && info.addr && info.authority) {
     if(!validateIdCard(info.id)){
       wx.showToast({
         title:'身份证号不正确,请重新上传',
         icon:'none'
       });
       return;
     }
      wx.showLoading({
        title: '保存中',
      }).then();

      const validDate = convertValidDate(info.validDate);

      // const [err] = await userInfoService.refreshOcrInfo({
      //   id: info.id,
      //   name: info.name,
      //   gender: info.gender,
      //   nationality: info.nationality,
      //   birth: dayjs(info.birth).unix(),
      //   addr: info.addr,
      //   idcardPortraitPath: info.idcardPortraitPath,
      //   idcardEmblemPath: info.idcardEmblemPath,
      //   portraitPath: info.portraitPath,
      //   authority: info.authority,
      //   validDateStart: dayjs(validDate.startDate).unix(),
      //   validDateEnd: validDate.endDate === '长期' ? 0 : dayjs(validDate.endDate).unix(),
      // });

      const [err] = await userInfoService.saveOcrInfo({
        id: info.id,
        name: info.name,
        gender: info.gender,
        nationality: info.nationality,
        birth: dayjs(info.birth).unix(),
        addr: info.addr,
        idcardPortraitPath: info.idcardPortraitPath,
        idcardEmblemPath: info.idcardEmblemPath,
        portraitPath: info.portraitPath,
        authority: info.authority,
        validDateStart: dayjs(validDate.startDate).unix(),
        validDateEnd: validDate.endDate === '长期' ? 0 : dayjs(validDate.endDate).unix(),
      });
      
      wx.hideLoading().then();

      if (err) {
        showToast(err);
      } else {
        if (this.routerType === 'bidding') {
          wx.redirectTo({
            url: `/lease/pages/enroll/tenant?leaseId=${this.leaseId}`,
          }).then();
        } else {
          wx.navigateBack().then();
        }

      }

    }else{
      wx.showToast({
        title:'身份证信息识别不全,请重新上传',
        icon:'none'
      });
    }

  },

});

export {};
page {
  box-sizing: border-box;
  padding-bottom: 176rpx;
}

.topic_box {
  margin: 16rpx auto;
  font-size: 28rpx;
  text-align: center;
  color: #666;
  line-height: 42rpx;
}

$upWd: 448rpx;
$upHg: 252rpx;
$pd: 20rpx;

.upload_box {
  box-sizing: border-box;
  width: $upWd + $pd * 2;
  height: $upHg + $pd * 2;
  margin: 32rpx auto 0;
  padding: $pd;
  background: #fcfcfc;
  border-radius: 12rpx;
  box-shadow: 0 0 3rpx 2rpx rgba(0,0,0,0.07);

  & + & {
    margin-top: 68rpx;
  }
  .upload_img {
    display: block;
    width: 100%;
    height: 100%;
  }
}

.upload_desc-box {
  width: $upWd + $pd * 2;
  margin: 24rpx auto 0;
}
.upload_desc {
  display: flex;
  align-items: center;
  width: 100%;
  font-size: 24rpx;
  color: #666;
  line-height: 42rpx;

  .desc_ft {
    $wd: 96rpx;

    flex: 0 0 $wd;
    width: $wd;
    text-align: right;
  }
  .desc_bd {
    padding-left: 30rpx;
  }
}

.footer_box {
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 50;
  box-sizing: border-box;
  width: 100%;
  padding: 40rpx 50rpx;
}

效果图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值