Skip to content

Instantly share code, notes, and snippets.

@aeknarinamn
Created September 24, 2022 08:19
Show Gist options
  • Save aeknarinamn/3bdc2b2f8dc733122df089cc986e01ee to your computer and use it in GitHub Desktop.
Save aeknarinamn/3bdc2b2f8dc733122df089cc986e01ee to your computer and use it in GitHub Desktop.
LINE WEBHOOK BY GROUP
<?php
/*
LINE Example Webhook Group v.1
*/
/*Function Write File LOG*/
file_put_contents('log.txt', file_get_contents('php://input') . PHP_EOL, FILE_APPEND);
/*Get Data From POST Http Request*/
$datas = file_get_contents('php://input');
/*Decode Json From LINE Data Body*/
$deCode = json_decode($datas,true);
/*GET Reply Token*/
$replyToken = $deCode['events'][0]['replyToken'];
/*GET Source Type*/
$sourceType = $deCode['events'][0]['source']['type'];
if($sourceType == 'group'){
/*GET GroupID*/
$groupId = $deCode['events'][0]['source']['groupId'];
/*GET Event Type*/
$groupEvent = $deCode['events'][0]['type'];
if($groupEvent == 'message'){
/*Message Type*/
$messageType = $deCode['events'][0]['message']['type'];
if($groupId == '<group id>'){
/*Example TEXT Message*/
$dataSendMessage['messages'][0] = getFormatTextMessage("Hello World");
/*Set Reply Token*/
$dataSendMessage['replyToken'] = $replyToken;
/*Json Encode*/
$encodeJson = json_encode($dataSendMessage);
/*Set URL*/
$functionals['url'] = "https://api.line.me/v2/bot/message/reply";
$functionals['token'] = getTokenData();
/*Function Send Message*/
$resp = sentMessage($encodeJson,$functionals);
/*Function Write File LOG*/
file_put_contents('log.txt', json_encode($resp) . PHP_EOL, FILE_APPEND);
}
}else{
}
}
/*Return HTTP Request 200*/
http_response_code(200);
function getFormatTextMessage($text)
{
$datas = [];
$datas['type'] = 'text';
$datas['text'] = $text;
return $datas;
}
function getTokenData()
{
$token = "<token>";
return $token;
}
function sentMessage($encodeJson,$datas)
{
$datasReturn = [];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $datas['url'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $encodeJson,
CURLOPT_HTTPHEADER => array(
"authorization: Bearer ".$datas['token'],
"cache-control: no-cache",
"content-type: application/json; charset=UTF-8",
),
));
$response = curl_exec($curl);
// dd($response);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
$datasReturn['result'] = 'E';
$datasReturn['message'] = $err;
} else {
if($response == "{}"){
$datasReturn['result'] = 'S';
$datasReturn['message'] = 'Success';
}else{
$datasReturn['result'] = 'E';
$datasReturn['message'] = $response;
}
}
return $datasReturn;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment