33 lines
1.0 KiB
TypeScript
33 lines
1.0 KiB
TypeScript
import { Platform } from 'react-native';
|
||
import {
|
||
retrieveVerificationCode,
|
||
startSmsHandling,
|
||
} from '@eabdullazyanov/react-native-sms-user-consent';
|
||
|
||
/** 用户点允许后,从短信正文取数字(优先 preferLength 位,否则取第一段数字) */
|
||
export function digitsFromSms(message: string, preferLength?: number): string {
|
||
if (preferLength) {
|
||
const exact = retrieveVerificationCode(message, preferLength);
|
||
if (exact) return exact;
|
||
}
|
||
const m = message.match(/\d+/);
|
||
return m ? m[0] : '';
|
||
}
|
||
|
||
/**
|
||
* SMS User Consent:系统弹窗,用户同意后才回调;无需 READ_SMS / app hash。
|
||
*/
|
||
export function startSmsUserConsentListener(
|
||
preferLength: number,
|
||
onDigits: (digits: string) => void,
|
||
): () => void {
|
||
if (Platform.OS !== 'android') return () => {};
|
||
|
||
return startSmsHandling((event) => {
|
||
const sms = event?.sms ?? '';
|
||
if (!sms) return;
|
||
const digits = digitsFromSms(sms, preferLength);
|
||
if (digits) onDigits(digits);
|
||
});
|
||
}
|