ส่งข้อความเข้า Line Notify ด้วย PHP

Posted by tospichai on May 22, 2021
profile
tospichai

Posted on May 22, 2021

#php #line

Line Notify คือ บริการที่ LINE ให้เราส่งข้อความ หรือแจ้งเตือนอัตโนมัติ ไม่ว่าจะส่งเข้าผ่าน Group หรือบัญชีส่วนตัว ผ่าน API ของ LINE โดยตรง

ขั้นตอนในการ ขอ Access Token

  1. เข้าไปที่ Line Notify
  2. เข้าสู่ระบบด้วยรหัส Line ของเรา
  3. คลิ๊กที่ชื่อของเราตรงมุมขวาบนแล้วเลือก My page
  4. กด Generate token จะขึ้นหน้าต่างขึ้นมา
  5. ด้านบนใส่ชื่อที่ต้องการให้ Line แสดง เวลาส่งข้อความมา
  6. ด้านล่างจะเลือกส่งหาตัวเราเองแบบ 1-on-1 หรือส่งให้ Group ได้
  7. กด Generate token
  8. จะปรากฎหน้าต่างขึ้นมาว่า Your token is {xxxx} ให้เรา Copy token ไว้

Code

นี้คือ function หลักที่ใช้ในการส่งข้อความ

    function notify_message($message){
        $LINE_API = "https://notify-api.line.me/api/notify";
        $LINE_TOKEN = "ใส่ Line_Token ตรงนี้";
        $queryData = array('message' => $message);
        $queryData = http_build_query($queryData,'','&');
        $headerOptions = array(
            'http'=>array(
                'method'=>'POST',
                'header'=> "Content-Type: application/x-www-form-urlencoded\r\n"
                        ."Authorization: Bearer ".$LINE_TOKEN."\r\n"
                        ."Content-Length: ".strlen($queryData)."\r\n",
                'content' => $queryData
            )
        );
        $context = stream_context_create($headerOptions);
        $result = file_get_contents($LINE_API,FALSE,$context);
        $res = json_decode($result);
        return $res;
    }

วิธีใช้

    notify_message("ข้อความที่ต้องการ");

ตั้งค่าชื่อเป็น test ส่งแบบ 1-on-1 และ notify_message(“เทส Line Notify”);

Login