105 lines
2.7 KiB
PHP
105 lines
2.7 KiB
PHP
<?php
|
||
|
||
declare(strict_types=1);
|
||
|
||
namespace app\common\service;
|
||
|
||
/**
|
||
* 按号码类型拼接各平台加好友链接
|
||
*/
|
||
class SplitFriendUrlBuilder
|
||
{
|
||
/**
|
||
* 构建跳转 URL;无法构建时返回空字符串
|
||
*
|
||
* @param string $whatsAppReplyText 仅 WhatsApp 类型使用,预填消息文案(urlencode 在内部处理)
|
||
*/
|
||
public static function build(
|
||
string $numberType,
|
||
string $number,
|
||
string $numberTypeCustom = '',
|
||
string $whatsAppReplyText = ''
|
||
): string {
|
||
$number = trim($number);
|
||
if ($number === '') {
|
||
return '';
|
||
}
|
||
|
||
switch ($numberType) {
|
||
case 'whatsapp':
|
||
return self::buildWhatsApp($number, $whatsAppReplyText);
|
||
case 'telegram':
|
||
return self::buildTelegram($number);
|
||
case 'line':
|
||
return self::buildLine($number);
|
||
case 'custom':
|
||
return self::buildCustom($number, $numberTypeCustom);
|
||
default:
|
||
return '';
|
||
}
|
||
}
|
||
|
||
/**
|
||
* WhatsApp:https://api.whatsapp.com/send?phone= 仅数字,可选 &text= 预填消息
|
||
*/
|
||
private static function buildWhatsApp(string $number, string $replyText = ''): string
|
||
{
|
||
$digits = preg_replace('/\D+/', '', $number) ?? '';
|
||
if ($digits === '') {
|
||
return '';
|
||
}
|
||
|
||
$url = 'https://api.whatsapp.com/send?phone=' . $digits;
|
||
$replyText = trim($replyText);
|
||
if ($replyText !== '') {
|
||
$url .= '&text=' . rawurlencode($replyText);
|
||
}
|
||
|
||
return $url;
|
||
}
|
||
|
||
/**
|
||
* Telegram:https://t.me/+ 号码(去掉前导 +)
|
||
*/
|
||
private static function buildTelegram(string $number): string
|
||
{
|
||
$id = ltrim($number, '+');
|
||
if ($id === '') {
|
||
return '';
|
||
}
|
||
|
||
return 'https://t.me/+' . $id;
|
||
}
|
||
|
||
/**
|
||
* Line:https://line.me/ti/p/~ 拼接号码
|
||
*/
|
||
private static function buildLine(string $number): string
|
||
{
|
||
return 'https://line.me/ti/p/~' . $number;
|
||
}
|
||
|
||
/**
|
||
* 自定义:号码字段即为完整链接(仅允许 http/https)
|
||
*/
|
||
private static function buildCustom(string $number, string $numberTypeCustom): string
|
||
{
|
||
$url = trim($number);
|
||
if ($url === '' && trim($numberTypeCustom) !== '') {
|
||
$url = trim($numberTypeCustom);
|
||
}
|
||
if ($url === '') {
|
||
return '';
|
||
}
|
||
if (!filter_var($url, FILTER_VALIDATE_URL)) {
|
||
return '';
|
||
}
|
||
$scheme = strtolower((string) parse_url($url, PHP_URL_SCHEME));
|
||
if (!in_array($scheme, ['http', 'https'], true)) {
|
||
return '';
|
||
}
|
||
|
||
return $url;
|
||
}
|
||
}
|