需求: 發送短信到用戶輸入手機, 要求可以自定義信息內容
問題: 沒有電信貓, 使用免費api接口無法自定義短信內容
解決方案: 通過4G網卡, 接在服務器上, 通過AT指令操作網卡, 發送短信
查閱發現, AT質量發送需要對信息進行多重編碼, 而且發送超時, 但實際發送成功, 問題還未完全解決
代碼如下:
1 <?php 2 send_message('8613800138000', '您好, 你正在申請注冊服務平台, 您的驗證碼是: 97431'); 3 4 function send_message($phone, $message) { 5 $phone = decode_phone($phone); 6 7 $message_center = decode_message_center('+8613010200500'); //此步驟似乎沒用 8 9 $message = decode_message($message); 10 11 $length = get_message_length($phone, $message); 12 13 set_time_limit(0); 14 15 //根據情況選擇COM口, 此處為COM4, 在管理設備中, 查看網絡解調器的COM口 16 17 exec('mode COM4: baud=115200 data=8 stop=1 parity=n xon=on'); 18 19 $fd = dio_open('COM4:', O_RDWR); 20 21 $ff = dio_stat($fd); 22 23 if (!$fd) { 24 die("failed open com4"); 25 } 26 27 //chr(13)是回車, chr(16)是Ctrl+Z 28 29 dio_write($fd, "AT+CMGF=0" . chr(13)); //設置發送模式為PDU 30 31 dio_write($fd, "AT+CMGS=" . $length . chr(13)); //發送信息長度 32 33 dio_write($fd, '11000D91' . $phone . '000800' . $message . chr(26) . chr(13)); //發送短信息 34 35 sleep(2); 36 37 dio_close($fd); 38 } 39 40 function decode_phone($phone) { 41 $phone = str_replace('+', '', $phone); 42 43 if (strlen($phone) % 2 !== 0) { 44 $phone = $phone . 'F'; 45 } 46 47 $newPhone = ''; 48 for ($i = 0; $i < strlen($phone); $i += 2) { 49 $newPhone = $newPhone . substr($phone, $i + 1, 1) . substr($phone, $i, 1); 50 } 51 52 return $newPhone; 53 } 54 55 function decode_message_center($phone) { 56 $newPhone = '91' . decode_phone($phone); 57 58 $len = strtoupper(dechex(strlen($newPhone) / 2)); 59 60 if (strlen($len) % 2 !== 0) { 61 $len = '0' . $len; 62 } 63 64 $newPhone = $len . $newPhone; 65 66 return $newPhone; 67 } 68 69 function decode_message($message) { 70 $newMessage = utf8_unicode($message); 71 72 $len = strtoupper(dechex(strlen($newMessage) / 2)); 73 74 if (strlen($len) % 2 !== 0) { 75 $len = '0' . $len; 76 } 77 78 $newMessage = $len . $newMessage; 79 80 return $newMessage; 81 } 82 83 function utf8_unicode($name) { 84 $name = iconv('UTF-8', 'UCS-2', $name); 85 $len = strlen($name); 86 $str = ''; 87 88 for ($i = 0; $i < $len - 1; $i = $i + 2) { 89 $c = $name[$i]; 90 $c2 = $name[$i + 1]; 91 if (ord($c) > 0) { //兩個字節的文字 92 $str .= base_convert(ord($c), 10, 16) . str_pad(base_convert(ord($c2), 10, 16), 2, 0, STR_PAD_LEFT); 93 } else { 94 $str .= str_pad(base_convert(ord($c2), 10, 16), 4, 0, STR_PAD_LEFT); 95 } 96 } 97 98 $str = strtoupper($str); //轉換為大寫 99 return $str; 100 } 101 102 function get_message_length($phone, $message) { 103 $str = '11000D91' . $phone . '000800' . $message; 104 105 $length = strlen($str) / 2; 106 107 if ($length < 10) { 108 $length = '0' . $length; 109 } 110 111 return $length; 112 }