|
| 1 | +import defaultsDeep from 'lodash-es/defaultsDeep' |
| 2 | +import { SHA256, HmacSHA256, enc } from 'crypto-js' |
| 3 | +import axios from 'axios' |
| 4 | + |
| 5 | +export class TcRequestError extends Error { |
| 6 | + code?: string |
| 7 | + |
| 8 | + constructor(message: string, code?: string) { |
| 9 | + super(message + (code ? ` [${code}]` : '')) |
| 10 | + this.name = 'TcRequestError' |
| 11 | + if (code) this.code = code |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +export class OcrClient { |
| 16 | + private config: { |
| 17 | + secretId: string |
| 18 | + secretKey: string |
| 19 | + region: string |
| 20 | + } |
| 21 | + private requestConfig = { |
| 22 | + host: 'ocr.tencentcloudapi.com', |
| 23 | + service: 'ocr', |
| 24 | + version: '2018-11-19', |
| 25 | + algorithm: 'TC3-HMAC-SHA256', |
| 26 | + httpRequestMethod: 'POST', |
| 27 | + canonicalUri: '/', |
| 28 | + canonicalQueryString: '', |
| 29 | + canonicalHeaders: |
| 30 | + 'content-type:application/json; charset=utf-8\nhost:ocr.tencentcloudapi.com\n', |
| 31 | + signedHeaders: 'content-type;host', |
| 32 | + } |
| 33 | + |
| 34 | + constructor(config: { secretId: string; secretKey: string; host?: string }) { |
| 35 | + this.config = defaultsDeep({}, config, { |
| 36 | + region: 'ap-shanghai', |
| 37 | + }) |
| 38 | + } |
| 39 | + |
| 40 | + async request(data: { dataUrl: string }): Promise<string[]> { |
| 41 | + const payload = { |
| 42 | + ImageBase64: data.dataUrl, |
| 43 | + } |
| 44 | + const signature = this.signPayload(payload) |
| 45 | + const headers = { |
| 46 | + Authorization: signature.authorization, |
| 47 | + 'Content-Type': 'application/json; charset=UTF-8', |
| 48 | + 'X-TC-Action': 'GeneralBasicOCR', |
| 49 | + 'X-TC-Timestamp': signature.timestamp, |
| 50 | + 'X-TC-Version': this.requestConfig.version, |
| 51 | + 'X-TC-Region': this.config.region, |
| 52 | + 'X-TC-RequestClient': `WXAPP_SDK_OcrSDK_1.1.0`, |
| 53 | + } |
| 54 | + |
| 55 | + return axios |
| 56 | + .request({ |
| 57 | + url: 'https://ocr.tencentcloudapi.com', |
| 58 | + data: payload, |
| 59 | + method: 'POST', |
| 60 | + headers, |
| 61 | + responseType: 'json', |
| 62 | + }) |
| 63 | + .then((res) => { |
| 64 | + if (res.data?.Response?.Error) { |
| 65 | + const error = res.data.Response.Error |
| 66 | + throw new TcRequestError(error.Message, error.Code) |
| 67 | + } |
| 68 | + |
| 69 | + if (!res.data?.Response?.TextDetections) { |
| 70 | + throw new TcRequestError('没有数据返回') |
| 71 | + } |
| 72 | + |
| 73 | + const detections = res.data.Response.TextDetections |
| 74 | + const result: string[] = [] |
| 75 | + |
| 76 | + detections.forEach( |
| 77 | + (item: { DetectedText: string; AdvancedInfo: string }) => { |
| 78 | + const advanceInfo: { |
| 79 | + Parag: { |
| 80 | + ParagNo: number |
| 81 | + } |
| 82 | + } = JSON.parse(item.AdvancedInfo) |
| 83 | + const index = advanceInfo.Parag.ParagNo - 1 |
| 84 | + |
| 85 | + if (result[index]) { |
| 86 | + result[index] += ` ${item.DetectedText}` |
| 87 | + } else { |
| 88 | + result.push(item.DetectedText) |
| 89 | + } |
| 90 | + }, |
| 91 | + ) |
| 92 | + |
| 93 | + return result |
| 94 | + }) |
| 95 | + } |
| 96 | + |
| 97 | + private signPayload( |
| 98 | + payload: Record<string, any>, |
| 99 | + ): { authorization: string; timestamp: number } { |
| 100 | + const hashedRequestPayload = SHA256(JSON.stringify(payload)) |
| 101 | + const canonicalRequest = [ |
| 102 | + this.requestConfig.httpRequestMethod, |
| 103 | + this.requestConfig.canonicalUri, |
| 104 | + this.requestConfig.canonicalQueryString, |
| 105 | + this.requestConfig.canonicalHeaders, |
| 106 | + this.requestConfig.signedHeaders, |
| 107 | + hashedRequestPayload, |
| 108 | + ].join('\n') |
| 109 | + const t = new Date() |
| 110 | + const date = t.toISOString().substr(0, 10) |
| 111 | + const timestamp = Math.round(t.getTime() / 1000) |
| 112 | + const credentialScope = `${date}/${this.requestConfig.service}/tc3_request` |
| 113 | + const hashedCanonicalRequest = SHA256(canonicalRequest) |
| 114 | + const stringToSign = [ |
| 115 | + this.requestConfig.algorithm, |
| 116 | + timestamp, |
| 117 | + credentialScope, |
| 118 | + hashedCanonicalRequest, |
| 119 | + ].join('\n') |
| 120 | + |
| 121 | + const secretDate = HmacSHA256(date, `TC3${this.config.secretKey}`) |
| 122 | + const secretService = HmacSHA256(this.requestConfig.service, secretDate) |
| 123 | + const secretSigning = HmacSHA256('tc3_request', secretService) |
| 124 | + |
| 125 | + const signature = enc.Hex.stringify(HmacSHA256(stringToSign, secretSigning)) |
| 126 | + |
| 127 | + return { |
| 128 | + authorization: |
| 129 | + `${this.requestConfig.algorithm} ` + |
| 130 | + `Credential=${this.config.secretId}/${credentialScope}, ` + |
| 131 | + `SignedHeaders=${this.requestConfig.signedHeaders}, ` + |
| 132 | + `Signature=${signature}`, |
| 133 | + timestamp, |
| 134 | + } |
| 135 | + } |
| 136 | +} |
0 commit comments