Search code examples
phpline-api

How to get LINE user mid using PHP SDK?


I use the LINE BOT API Trial SDK PHP (https://github.com/line/line-bot-sdk-php).

But, for this method:

$res = $bot->sendText(['TARGET_MID'], 'Message');

How to get the user's MID to send them a message?

Thanks for help.


Solution

  • 1) A very quick way to get the mid of an interactive user (more of a fun hack, really) is to register a callback URL as per the API instructions, then capture the POST data to that URL like so:

    // /callback/index.php
    <?php
    $postdata = file_get_contents("php://input");
    @file_get_contents('https://'.$_SERVER['SERVER_NAME'].'/LINE/' . json_encode($postdata));
    

    Next, scan the QR code in the channel console and add your trial bot to your LINE account. After that is done, send it a quick "Hello!" text.

    You could then save the POST data to a text file if you wish, or you could check the server logs. For example, you might see something like this:

    163.128.118.223 - - [03/Sep/2016:07:25:25 -0700] "POST /line/callback/ HTTP/1.1" 200 - "-" "ChannelEventDispatcher/1.0"
    106.152.218.107 - - [03/Sep/2016:07:25:25 -0700] "GET /LINE/{\"result\":[{\"content\":{\"toType\":1,\"createdTime\":1472114754839,\"from\":\"ub7dbd4a12c322f6c0117773d739c55a4\",\"location\":null,\"id\":\"4357194057879\",\"to\":[\"u2b6a4ba287028dee7291122094dac827\"],\"text\":\"Hello!\",\"contentMetadata\":{\"AT_RECV_MODE\":\"2\",\"SKIP_BADGE_COUNT\":\"true\"},\"deliveredTime\":0,\"contentType\":1,\"seq\":null},\"createdTime\":1472912724868,\"eventType\":\"138311609000106301\",\"from\":\"u236d23c2e36bd87217655609a1c31cb8\",\"fromChannel\":1241102815,\"id\":\"WB1519-3102846635\",\"to\":[\"u2b6a4ba287028dee7291122094dac827\"],\"toChannel\":1462261375}]} HTTP/1.1" 404 15 "-" "-"
    

    The \"from\":\"ub7dbd4a12c322f6c0117773d739c55a4\" is the pertinent part.


    2) If you'd like to get started with receiving messages, you can start like this as your callback script. Simply send your BOT the message 'mid' and it should respond with your mid.

    example of a mid reply

    Here is a starting callback script I made with signature verification included for you.

    // /callback/index.php
    <?php
    // Show all errors for testing
    error_reporting(E_ALL);
    
    // SDK is installed via composer
    require_once __DIR__ . "/includes/vendor/autoload.php";
    
    use LINE\LINEBot;
    use LINE\LINEBot\HTTPClient\GuzzleHTTPClient;
    
    // Set these
    $config = [
        'channelId' => LINE_CHANNEL_ID,
        'channelSecret' => LINE_CHANNEL_SECRET,
        'channelMid' => LINE_CHANNEL_MID,
    ];
    $sdk = new LINEBot($config, new GuzzleHTTPClient($config));
    
    $postdata = @file_get_contents("php://input");
    $messages = $sdk->createReceivesFromJSON($postdata);
    
    // Verify the signature
    // REF: http://line.github.io/line-bot-api-doc/en/api/callback/post.html#signature-verification
    $sigheader = 'X-LINE-ChannelSignature';
    // REF: http://stackoverflow.com/a/541450
    $signature = @$_SERVER[ 'HTTP_'.strtoupper(str_replace('-','_',$sigheader)) ];
    if($signature && $sdk->validateSignature($postdata, $signature)) {
        // Next, extract the messages
        if(is_array($messages)) {
            foreach ($messages as $message) {
                if ($message instanceof LINEBot\Receive\Message\Text) {
                    $text = $message->getText();
                    if ($text == "mid") {
                        $fromMid = $message->getFromMid();
    
                        // Send the mid back to the sender and check if the message was delivered
                        $result = $sdk->sendText([$fromMid], 'mid: ' . $fromMid);
                        if(!$result instanceof LINE\LINEBot\Response\SucceededResponse) {
                            error_log('LINE error: ' . json_encode($result));
                        }
                    } else {
                        // Process normally, or do nothing
                    }
                } else {
                    // Process other types of LINE messages like image, video, sticker, etc.
                }
            }
        } // Else, error
    } else {
        error_log('LINE signatures didn\'t match');
    }