I’m working on a Telegram bot using PHP and I want to collect the user’s phone number. I tried implementing a keyboard button with contact request functionality but it’s not working properly.
Here’s my current code:
sendTelegramMessage("requestMessage", array(
'chat_id' => $userId,
"text" => 'Would you like to share your contact details?',
'reply_markup' => array(
'keyboard' => array(
'text'=>"SHARE CONTACT",
'request_contact'=>true
),
'one_time_keyboard' => true,
'resize_keyboard' => true
)
));
The keyboard appears but the contact sharing feature doesn’t seem to work. I’m not sure if I’m structuring the keyboard array correctly or if there’s something else I’m missing. Has anyone encountered this issue before? What might be causing this problem?
yep, nested arrays r super important - telegram’s api is picky bout structure. also, make sure to handle the contact response properly when users share it. u’ll get a contact obj in the message update with a phone_number field. don’t forget to json_encode your reply_markup array before sending.
Indeed, the structure of your array is a key issue. However, there’s another important aspect you need to be aware of. When a user shares their contact, the response is sent back as a message update that includes a contact object instead of standard text. Make sure your webhook handler checks for the contact field in the incoming messages. I had to adapt my message processing logic to account for contact messages in addition to text messages. The phone number will be found in $update['message']['contact']['phone_number'], and if the user shares their details, you’ll also receive their first and last name. It’s vital to manage the contact response correctly; otherwise, you might mistakenly assume the button isn’t functioning when it is.
Your keyboard array structure is messed up. You’re missing the proper nesting for the button - keyboards need rows of buttons, not individual button properties at the top level.
Here’s the fix:
'reply_markup' => array(
'keyboard' => array(
array(
array(
'text' => 'SHARE CONTACT',
'request_contact' => true
)
)
),
'one_time_keyboard' => true,
'resize_keyboard' => true
)
I ran into the same thing when I started with Telegram Bot API. The keyboard array expects an array of rows, and each row needs an array of button objects. Fix the nesting and your contact request should work - users will get the native contact sharing dialog when they tap the button.