I’m trying to create a Telegram bot that can request a user’s phone number. Here’s my PHP code:
$response = sendTelegramMessage([
'chat_id' => $userChatId,
'text' => 'Would you like to share your phone number?',
'reply_markup' => [
'keyboard' => [
[
['text' => 'SHARE CONTACT', 'request_contact' => true]
]
],
'one_time_keyboard' => true,
'resize_keyboard' => true
]
]);
But it’s not working as expected. The button shows up but doesn’t seem to request the contact info when pressed. Am I missing something in the code? How can I fix this to properly request and store the user’s phone number?
Any help would be appreciated. Thanks!
Your code looks correct for displaying the contact sharing button. The issue might be in how you’re handling the response. When a user shares their contact, Telegram sends an update with a ‘contact’ field. You need to process this in your webhook.
Here’s a snippet to capture the shared contact:
$update = json_decode(file_get_contents('php://input'), true);
if (isset($update['message']['contact'])) {
$phoneNumber = $update['message']['contact']['phone_number'];
// Store or process $phoneNumber as needed
}
Ensure your webhook is set up correctly to receive these updates. Also, double-check your bot’s privacy settings in BotFather to allow it to receive user data. Let me know if you need further clarification on implementing this.
I’ve encountered the same issue with my Telegram bots. Your code appears correct, but the problem usually lies in processing the response. When I worked on this, I learned that the contact info is sent in a separate ‘contact’ field rather than as part of a regular message. This means you need to check for that specific field in your webhook to extract the phone number. Also, ensure that your webhook is properly set up and that your bot’s privacy settings in BotFather allow access to user data. I hope this helps.
hey emma, i had similar issue before. make sure ur bot has the right permissions set in BotFather. also, check if ur handling the contact data correctly in ur webhook. sometimes its tricky to get the data from the update. hope this helps!