How to implement contact sharing with KeyboardButton in Telegram Bot API

I’m working on a Telegram bot using PHP and I want to collect user phone numbers. I’m having trouble getting the contact request feature to work properly.

Here’s my current code:

sendTelegramMessage(array(
    'chat_id' => $user_id,
    '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 button appears but it doesn’t seem to trigger the contact sharing functionality. I’m not sure if I’m structuring the keyboard markup correctly. Has anyone encountered this issue before? What’s the proper way to set up a contact request button in the Telegram Bot API?

Your keyboard structure’s wrong. You need to wrap buttons in proper array layers - each button goes in its own array element inside a row array. 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 hit the same issue when I first started collecting contacts in my bots. Telegram’s API wants a two-dimensional array - outer array for rows, inner arrays for button objects. Get this nesting right and the contact sharing prompt will work when users tap the button.

Had the same issue with my first contact bot. Your keyboard structure’s the problem, but there’s another gotcha - you need to handle the contact response right in your webhook. When someone shares their contact, Telegram sends a message object with a ‘contact’ field, not regular text. Check for $message['contact']['phone_number'] in your message handler. Contact sharing only works in private chats too, not groups - might be why your tests aren’t working. The nested array structure others mentioned is spot on, just don’t forget to actually process the contact data when it comes back.

i think ur keyboard array structure’s off. u gotta enclose the button in an extra array, like this: 'keyboard' => array(array(array('text' => 'SHARE CONTACT', 'request_contact' => true))). it expects an array of rows, and each row has to be an array of buttons.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.