เนื้อหาในตอนต่อไปนี้ จะเน้นไปที่การประยุกต์ การใช้งาน LIFF app
หลักๆ จะเน้นไปที่ตัวอย่างการสร้าง web app สำหรับใช้งานใน LINE LIFF
โดยจะมีตัวอย่างด้วยกัน 3 ตัวอย่าง
ตัวอย่างแรก จะเป็นการใช้งาน LIFF SDK ส่วนของ Server API เราจะสร้าง
web app ด้วย PHP เป็น app สำหรับจัดการรายการ LIFF app อีกที ซึ่ง เราทราบมาแล้ว
ว่า ในการกำหนด LIFF app เราสามารถเข้าไปจัดการหรือกำหนดค่าในส่วนของ console
สำหรับสิ่งที่เราจะได้เรียนรู้ไปในตัวอย่างแรกคือ การใช้งาน Server API ของ LIFF SDK
ในการใช้คำสั่ง เพิ่ม ลบ และแก้ไข รายการ LIFF app โดยเราจะทำผ่านคำสั่งต่างๆ ของ
Line bot sdk ซึ่งมีชุดคำสั่งเตรียมพร้อมให้เราเกือบหมดแล้ว แต่อาจจะมีประยุกต์เพิ่มเติมอีกนิดหน่อย
ในบางคำสั่งที่ไม่รองรับ เราจะได้เรียนรู้การสร้าง Flex Message โดยใช้ XML เพื่อสร้างข้อความเมนู
สำหรับจัดการ LIFF app ผ่าน Messaging API เหล่านี้เป็นต้น
ตัวอย่างที่สองจะคล้ายกับตัวอย่างแรก เป็น web app จัดการ LIFF app แต่ใช้ในรูปแบบ ajax แทน
การเรียกผ่านไฟล์ PHP โดยตรง ซึ่งการใช้งานในรูปแบบ ajax จะเห็นผลถึงรูปแบบการ่ทำงานที่เร็วและ
ให้ความรู้สึก mobile app มากกว่าในแบบ PHP ปกติ ที่จะดูเหมือน web app ทั่วไป
ตัวอย่างที่สามจะเป็น Drawing app เป็น web app สำหรับให้ผู้ใช้ สามารถที่จะวาดรูปตามต้องการ แล้ว
ส่งกลับเข้าไปในห้องสนทนาได้ ซึ่งการทำงานเกี่ยวกับการวาดรูป เราจะใช้ jquery plugin เข้ามาช่วย
โดยมีการประยุกต์เพิ่มเติม เพื่อให้มีความสามารถต้องการ และมีการใช้ image library เกี่ยวกับการจัดการ
รูปภาพเข้ามาร่วมอีกด้วย
อย่างไรก็ตาม จะเน้นไปที่ตัวอย่างโค้ดเป็นสำคัญ เพราะถ้าลงในรายละเอียดแต่ละตัวอย่างมากเกินไป
อาจจะทำให้เนื้อหายาวมาก
สร้าง LINE LIFF Manager
จากตอนที่แล้ว http://niik.in/901
เราจำเป็นต้องมี LIFF app อย่างน้อยหนึ่งรายการ เพื่อใช้ในการดึงมาแสดง ด้วย Flex Message สามารถเข้าไป
สร้าง LIFF app เบื้องต้นตามลิ้งค์ด้านบน
ไฟล์ bot_action.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 | <?php ///////////// ส่วนของการเรียกใช้งาน class ผ่าน namespace use LINE\LINEBot; use LINE\LINEBot\HTTPClient; use LINE\LINEBot\HTTPClient\CurlHTTPClient; use LINE\LINEBot\Event; use LINE\LINEBot\Event\BaseEvent; use LINE\LINEBot\Event\MessageEvent; use LINE\LINEBot\Event\AccountLinkEvent; use LINE\LINEBot\Event\MemberJoinEvent; use LINE\LINEBot\MessageBuilder; use LINE\LINEBot\MessageBuilder\TextMessageBuilder; use LINE\LINEBot\MessageBuilder\StickerMessageBuilder; use LINE\LINEBot\MessageBuilder\ImageMessageBuilder; use LINE\LINEBot\MessageBuilder\LocationMessageBuilder; use LINE\LINEBot\MessageBuilder\AudioMessageBuilder; use LINE\LINEBot\MessageBuilder\VideoMessageBuilder; use LINE\LINEBot\ImagemapActionBuilder; use LINE\LINEBot\ImagemapActionBuilder\AreaBuilder; use LINE\LINEBot\ImagemapActionBuilder\ImagemapMessageActionBuilder ; use LINE\LINEBot\ImagemapActionBuilder\ImagemapUriActionBuilder; use LINE\LINEBot\MessageBuilder\Imagemap\BaseSizeBuilder; use LINE\LINEBot\MessageBuilder\ImagemapMessageBuilder; use LINE\LINEBot\MessageBuilder\MultiMessageBuilder; use LINE\LINEBot\TemplateActionBuilder; use LINE\LINEBot\TemplateActionBuilder\DatetimePickerTemplateActionBuilder; use LINE\LINEBot\TemplateActionBuilder\MessageTemplateActionBuilder; use LINE\LINEBot\TemplateActionBuilder\PostbackTemplateActionBuilder; use LINE\LINEBot\TemplateActionBuilder\UriTemplateActionBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder; use LINE\LINEBot\MessageBuilder\TemplateMessageBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder\ButtonTemplateBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder\CarouselTemplateBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder\CarouselColumnTemplateBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder\ConfirmTemplateBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder\ImageCarouselTemplateBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder\ImageCarouselColumnTemplateBuilder; use LINE\LINEBot\QuickReplyBuilder; use LINE\LINEBot\QuickReplyBuilder\QuickReplyMessageBuilder; use LINE\LINEBot\QuickReplyBuilder\ButtonBuilder\QuickReplyButtonBuilder; use LINE\LINEBot\TemplateActionBuilder\CameraRollTemplateActionBuilder; use LINE\LINEBot\TemplateActionBuilder\CameraTemplateActionBuilder; use LINE\LINEBot\TemplateActionBuilder\LocationTemplateActionBuilder; use LINE\LINEBot\RichMenuBuilder; use LINE\LINEBot\RichMenuBuilder\RichMenuSizeBuilder; use LINE\LINEBot\RichMenuBuilder\RichMenuAreaBuilder; use LINE\LINEBot\RichMenuBuilder\RichMenuAreaBoundsBuilder; use LINE\LINEBot\Constant\Flex\ComponentIconSize; use LINE\LINEBot\Constant\Flex\ComponentImageSize; use LINE\LINEBot\Constant\Flex\ComponentImageAspectRatio; use LINE\LINEBot\Constant\Flex\ComponentImageAspectMode; use LINE\LINEBot\Constant\Flex\ComponentFontSize; use LINE\LINEBot\Constant\Flex\ComponentFontWeight; use LINE\LINEBot\Constant\Flex\ComponentMargin; use LINE\LINEBot\Constant\Flex\ComponentSpacing; use LINE\LINEBot\Constant\Flex\ComponentButtonStyle; use LINE\LINEBot\Constant\Flex\ComponentButtonHeight; use LINE\LINEBot\Constant\Flex\ComponentSpaceSize; use LINE\LINEBot\Constant\Flex\ComponentGravity; use LINE\LINEBot\MessageBuilder\FlexMessageBuilder; use LINE\LINEBot\MessageBuilder\Flex\BubbleStylesBuilder; use LINE\LINEBot\MessageBuilder\Flex\BlockStyleBuilder; use LINE\LINEBot\MessageBuilder\Flex\ContainerBuilder\BubbleContainerBuilder; use LINE\LINEBot\MessageBuilder\Flex\ContainerBuilder\CarouselContainerBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\BoxComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\ButtonComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\IconComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\ImageComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\SpacerComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\FillerComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\SeparatorComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\TextComponentBuilder; // ไฟล์ฟังก์ชั่นสำหรับแปลง xml เป็น flex require_once ( "flex_gen.php" ); // ส่วนของการทำงาน if (! is_null ( $events )){ // ถ้า bot ถูก invite เพื่อเข้า Join Event ให้ bot ส่งข้อความใน GROUP ว่าเข้าร่วม GROUP แล้ว if (! is_null ( $eventJoin )){ $textReplyMessage = "ขอเข้าร่วมด้วยน่ะ $sourceType ID:: " . $sourceId ; $replyData = new TextMessageBuilder( $textReplyMessage ); } // ถ้า bot ออกจาก สนทนา จะไม่สามารถส่งข้อความกลับได้ เนื่องจากไม่มี replyToken if (! is_null ( $eventLeave )){ } // ถ้า bot ถูกเพื่มเป้นเพื่อน หรือถูกติดตาม หรือ ยกเลิกการ บล็อก if (! is_null ( $eventFollow )){ $textReplyMessage = "ขอบคุณที่เป็นเพื่อน และติดตามเรา" ; $replyData = new TextMessageBuilder( $textReplyMessage ); } // ถ้า bot ถูกบล็อก หรือเลิกติดตาม จะไม่สามารถส่งข้อความกลับได้ เนื่องจากไม่มี replyToken if (! is_null ( $eventUnfollow )){ } // ถ้ามีสมาชิกคนอื่น เข้ามาร่วมใน room หรือ group // room คือ สมมติเราคุยกับ คนหนึ่งอยู่ แล้วเชิญคนอื่นๆ เข้ามาสนทนาด้วย จะกลายเป็นห้องใหม่ // group คือ กลุ่มที่เราสร้างไว้ มีชื่อกลุ่ม แล้วเราเชิญคนอื่นเข้ามาในกลุ่ม เพิ่มร่วมสนทนาด้วย if (! is_null ( $eventMemberJoined )){ $arr_joinedMember = $eventObj ->getEventBody(); $joinedMember = $arr_joinedMember [ 'joined' ][ 'members' ][0]; if (! is_null ( $groupId ) || ! is_null ( $roomId )){ if ( $eventObj ->isGroupEvent()){ foreach ( $joinedMember as $k_user => $v_user ){ if ( $k_user == "userId" ){ $joined_userId = $v_user ; } } $response = $bot ->getGroupMemberProfile( $groupId , $joined_userId ); } if ( $eventObj ->isRoomEvent()){ foreach ( $joinedMember as $k_user => $v_user ){ if ( $k_user == "userId" ){ $joined_userId = $v_user ; } } $response = $bot ->getRoomMemberProfile( $roomId , $joined_userId ); } } else { $response = $bot ->getProfile( $userId ); } if ( $response ->isSucceeded()) { $userData = $response ->getJSONDecodedBody(); // return array // $userData['userId'] // $userData['displayName'] // $userData['pictureUrl'] // $userData['statusMessage'] $textReplyMessage = 'สวัสดีครับ คุณ ' . $userData [ 'displayName' ]; } else { $textReplyMessage = 'สวัสดีครับ ยินดีต้อนรับ' ; } // $textReplyMessage = "ยินดีต้อนรับกลับมาอีกครั้ง ".json_encode($joinedMember); $replyData = new TextMessageBuilder( $textReplyMessage ); } // ถ้ามีสมาชิกคนอื่น ออกจากก room หรือ group จะไม่สามารถส่งข้อความกลับได้ เนื่องจากไม่มี replyToken if (! is_null ( $eventMemberLeft )){ } // ถ้ามีกาาเชื่อมกับบัญชี LINE กับระบบสมาชิกของเว็บไซต์เรา if (! is_null ( $eventAccountLink )){ // หลักๆ ส่วนนี้ใช้สำรหบัเพิ่มความภัยในการเชื่อมบัญตี LINE กับระบบสมาชิกของเว็บไซต์เรา $textReplyMessage = "AccountLink ทำงาน " . $replyToken . " Nonce: " . $eventObj ->getNonce(); $replyData = new TextMessageBuilder( $textReplyMessage ); } // ถ้าเป็น Postback Event if (! is_null ( $eventPostback )){ $dataPostback = NULL; $paramPostback = NULL; // แปลงข้อมูลจาก Postback Data เป็น array parse_str ( $eventObj ->getPostbackData(), $dataPostback ); // ดึงค่า params กรณีมีค่า params $paramPostback = $eventObj ->getPostbackParams(); $moreResult = "" ; if (isset( $dataPostback [ 'action' ]) && $dataPostback [ 'action' ]== "more_richmenu" ){ $respRichMenu = $bot ->linkRichMenu( $userId , $dataPostback [ 'richmenuid' ]); $moreResult = $respRichMenu ->getRawBody(); $result = json_decode( $respRichMenu ->getRawBody(),TRUE); } if (isset( $dataPostback [ 'action' ]) && $dataPostback [ 'action' ]== "back_richmenu" ){ $respRichMenu = $bot ->unlinkRichMenu( $userId ); $moreResult = $respRichMenu ->getRawBody(); $result = json_decode( $respRichMenu ->getRawBody(),TRUE); } if (isset( $dataPostback [ 'action' ]) && $dataPostback [ 'action' ]== "delete_richmenu" ){ $respRichMenu = $bot ->deleteRichMenu( $dataPostback [ 'richMenuId' ]); $moreResult = $respRichMenu ->getRawBody(); $result = json_decode( $respRichMenu ->getRawBody(),TRUE); } if (isset( $dataPostback [ 'action' ]) && $dataPostback [ 'action' ]== "get_richmenu" ){ $respRichMenu = $bot ->getRichMenu( $dataPostback [ 'richMenuId' ]); $moreResult = $respRichMenu ->getRawBody(); $result = json_decode( $respRichMenu ->getRawBody(),TRUE); } if (isset( $dataPostback [ 'action' ]) && $dataPostback [ 'action' ]== "s_default_richmenu" ){ $respRichMenu = $httpClient ->post( "https://api.line.me/v2/bot/user/all/richmenu/" . $dataPostback [ 'richMenuId' ], array ()); $moreResult = $respRichMenu ->getRawBody(); $result = json_decode( $respRichMenu ->getRawBody(),TRUE); } if (isset( $dataPostback [ 'action' ]) && $dataPostback [ 'action' ]== "c_default_richmenu" ){ $moreResult = $respRichMenu ->getRawBody(); $result = json_decode( $respRichMenu ->getRawBody(),TRUE); } if (isset( $dataPostback [ 'action' ]) && $dataPostback [ 'action' ]== "g_default_richmenu" ){ $moreResult = $respRichMenu ->getRawBody(); $result = json_decode( $respRichMenu ->getRawBody(),TRUE); } if (isset( $dataPostback [ 'action' ]) && $dataPostback [ 'action' ]== "upload_richmenu" ){ $richMenuImg = str_replace ( 'Rich Menu ' , '' , $dataPostback [ 'richMenuName' ]); if (! file_exists ( "rich-menu/rich-menu-0" . $richMenuImg . ".png" )){ $richMenuImg = substr ( str_replace ( 'Rich Menu ' , '' , $dataPostback [ 'richMenuName' ]),0,1); } $respRichMenu = $bot ->uploadRichMenuImage( $dataPostback [ 'richMenuId' ], "rich-menu/rich-menu-0" . $richMenuImg . ".png" , "image/png" ); $moreResult = $respRichMenu ->getRawBody(); $result = json_decode( $respRichMenu ->getRawBody(),TRUE); } // ทดสอบแสดงข้อความที่เกิดจาก Postaback Event $textReplyMessage = "ข้อความจาก Postback Event Data : DataPostback = " ; $textReplyMessage .= json_encode( $dataPostback ); $textReplyMessage .= " ParamPostback = " .json_encode( $paramPostback ); $textReplyMessage .= " RsponseMore = " . $moreResult ; $replyData = new TextMessageBuilder( $textReplyMessage ); } // ถ้าเป้น Message Event if (! is_null ( $eventMessage )){ // สร้างตัวแปรเก็ยค่าประเภทของ Message จากทั้งหมด 7 ประเภท $typeMessage = $eventObj ->getMessageType(); // text | image | sticker | location | audio | video | file // เก็บค่า id ของข้อความ $idMessage = $eventObj ->getMessageId(); // ถ้าเป็นข้อความ if ( $typeMessage == 'text' ){ $userMessage = $eventObj -> getText (); // เก็บค่าข้อความที่ผู้ใช้พิมพ์ } // ถ้าเป็น image if ( $typeMessage == 'image' ){ } // ถ้าเป็น audio if ( $typeMessage == 'audio' ){ } // ถ้าเป็น video if ( $typeMessage == 'video' ){ } // ถ้าเป็น file if ( $typeMessage == 'file' ){ $FileName = $eventObj ->getFileName(); $FileSize = $eventObj ->getFileSize(); } // ถ้าเป็น image หรือ audio หรือ video หรือ file และต้องการบันทึกไฟล์ if (preg_match( '/image|audio|video|file/' , $typeMessage )){ $responseMedia = $bot ->getMessageContent( $idMessage ); if ( $responseMedia ->isSucceeded()) { // คำสั่ง getRawBody() ในกรณีนี้ จะได้ข้อมูลส่งกลับมาเป็น binary // เราสามารถเอาข้อมูลไปบันทึกเป็นไฟล์ได้ $dataBinary = $responseMedia ->getRawBody(); // return binary // ดึงข้อมูลประเภทของไฟล์ จาก header $fileType = $responseMedia ->getHeader( 'Content-Type' ); switch ( $fileType ){ case (preg_match( '/^application/' , $fileType ) ? true : false): // $fileNameSave = $FileName; // ถ้าต้องการบันทึกเป็นชื่อไฟล์เดิม $arr_ext = explode ( "." , $FileName ); $ext = array_pop ( $arr_ext ); $fileNameSave = time(). "." . $ext ; break ; case (preg_match( '/^image/' , $fileType ) ? true : false): list( $typeFile , $ext ) = explode ( "/" , $fileType ); $ext = ( $ext == 'jpeg' || $ext == 'jpg' )? "jpg" : $ext ; $fileNameSave = time(). "." . $ext ; break ; case (preg_match( '/^audio/' , $fileType ) ? true : false): list( $typeFile , $ext ) = explode ( "/" , $fileType ); $fileNameSave = time(). "." . $ext ; break ; case (preg_match( '/^video/' , $fileType ) ? true : false): list( $typeFile , $ext ) = explode ( "/" , $fileType ); $fileNameSave = time(). "." . $ext ; break ; } $botDataFolder = 'botdata/' ; // โฟลเดอร์หลักที่จะบันทึกไฟล์ $botDataUserFolder = $botDataFolder . $userId ; // มีโฟลเดอร์ด้านในเป็น userId อีกขั้น if (! file_exists ( $botDataUserFolder )) { // ตรวจสอบถ้ายังไม่มีให้สร้างโฟลเดอร์ userId mkdir ( $botDataUserFolder , 0777, true); } // กำหนด path ของไฟล์ที่จะบันทึก $fileFullSavePath = $botDataUserFolder . '/' . $fileNameSave ; // file_put_contents($fileFullSavePath,$dataBinary); // เอา comment ออก ถ้าต้องการทำการบันทึกไฟล์ $textReplyMessage = "บันทึกไฟล์เรียบร้อยแล้ว $fileNameSave" ; $replyData = new TextMessageBuilder( $textReplyMessage ); // $failMessage = json_encode($fileType); // $failMessage = json_encode($responseMedia->getHeaders()); // $replyData = new TextMessageBuilder($failMessage); } else { // $failMessage = json_encode($idMessage.' '.$responseMedia->getHTTPStatus() . ' ' . $responseMedia->getRawBody()); // $failMessage = json_encode((array)$eventObj); // ดูโครงสร้างข้อมูล $failMessage = "ไม่ต้องส่งข้อความใดๆ กลับ" ; $replyData = new TextMessageBuilder( $failMessage ); exit ; } } // ถ้าเป็น sticker if ( $typeMessage == 'sticker' ){ $packageId = $eventObj ->getPackageId(); $stickerId = $eventObj ->getStickerId(); } // ถ้าเป็น location if ( $typeMessage == 'location' ){ $locationTitle = $eventObj ->getTitle(); $locationAddress = $eventObj ->getAddress(); $locationLatitude = $eventObj ->getLatitude(); $locationLongitude = $eventObj ->getLongitude(); } switch ( $typeMessage ){ // กำหนดเงื่อนไขการทำงานจาก ประเภทของ message case 'text' : // ถ้าเป็นข้อความ $userMessage = strtolower ( $userMessage ); // แปลงเป็นตัวเล็ก สำหรับทดสอบ switch ( $userMessage ) { case "liff>" : // ส่วนทดสอบโต้ตอบ ให้แสดง LIFF Manager // ดึงข้อมูลของ LIFF app ทั้งหมด $resultListLIFF = json_decode( $respLIFF ->getRawBody(),TRUE); $xmlListLIFF = "" ; // สร้างตัวแปร สำหรับเก็บรูปแบบ xml ที่มีการวนลูป if ( $resultListLIFF ){ // ตรวจสอบข้อมูล ว่ามีรายการ LIFF app foreach ( $resultListLIFF [ 'apps' ] as $liffData ){ // วนลูปแสดงรายการ $xmlListLIFF .=' <box layout= "horizontal" > <text action= "u(line://app/'.$liffData['liffId'].')" gravity= "center" > '.$liffData[' description '].' </text> <button flex= "0" height= "sm" style= "link" color= "#00CC33" action= "u('.$LIFFappManagerURL.'?section=edit&liffid='.$liffData['liffId'].')" >Edit</button> </box> <separator /> '; } } $xmlstr = <<<XML <noncarousel> <bubble direction= "ltr" > <header backgroundColor= "#F7F7F7" > <box layout= "vertical" > <text align= "center" size= "xl" weight= "bold" >LIFF Manager</text> </box> </header> <body separator= "true" > <box layout= "vertical" spacing= "md" > { $xmlListLIFF } </box> </body> <footer> <box layout= "vertical" > <button style= "primary" action= "u({$LIFFappManagerURL})" color= "#3F48CC" >Add LIFF</button> </box> </footer> </bubble> </noncarousel> XML; $textReplyMessage = createFlex( $xmlstr ); $replyData = new FlexMessageBuilder( "Flex from XML" , $textReplyMessage ); break ; case (preg_match( '/^cr-/' , $userMessage ) ? true : false): $paramRichMenu = explode ( ">" , $userMessage ); if (!isset( $paramRichMenu ) || ! is_array ( $paramRichMenu ) || count ( $paramRichMenu )<3){ exit ; } $patternSet = $paramRichMenu [0]; $numberID = $paramRichMenu [1]; $actionSet = $paramRichMenu [2]; $actionArr_prepare = array (); if (isset( $actionSet )){ $actionArr_prepare = explode ( ")" , $actionSet ); array_pop ( $actionArr_prepare ); } $imgTypePattern = str_replace ( "cr-" , "" , $patternSet ); $areaBound_arr = array ( "a" => array (0,0,833,843), "b" => array (833,0,833,843), "c" => array (1666,0,834,843), "d" => array (0,843,833,843), "e" => array (833,843,833,843), "f" => array (1666,843,834,843), "g" => array (0,0,1250,843), "h" => array (1250,0,1250,843), "i" => array (0,843,1250,843), "j" => array (1250,843,1250,843), "k" => array (0,0,2500,843), "l" => array (0,0,1666,1686), "m" => array (0,843,2500,843), "n" => array (0,0,1250,1686), "o" => array (1250,0,1250,1686), "p" => array (0,0,2500,1686) ); $imgTypePatternArea_arr = array ( "1" => array ( "a" , "b" , "c" , "d" , "e" , "f" ), "2" => array ( "g" , "h" , "i" , "j" ), "3" => array ( "k" , "d" , "e" , "f" ), "4" => array ( "l" , "c" , "f" ), "5" => array ( "k" , "m" ), "6" => array ( "n" , "o" ), "7" => array ( "p" ) ); function makeFRM( $imgType ){ global $areaBound_arr , $imgTypePatternArea_arr , $actionSet , $actionArr_prepare ; $dataArr = array (); $Area_arr = $imgTypePatternArea_arr [ $imgType ]; for ( $i =1; $i <= count ( $imgTypePatternArea_arr [ $imgType ]); $i ++){ if (preg_match( '/^p\(/' , $actionArr_prepare [ $i -1])){ list( $ac , $data ) = explode ( "(" , $actionArr_prepare [ $i -1]); $actionVal = new PostbackTemplateActionBuilder( 'p' , $data ); } elseif (preg_match( '/^m\(/' , $actionArr_prepare [ $i -1])){ list( $ac , $data ) = explode ( "(" , $actionArr_prepare [ $i -1]); $actionVal = new MessageTemplateActionBuilder( 'm' , $data ); } elseif (preg_match( '/^u\(/' , $actionArr_prepare [ $i -1])){ list( $ac , $data ) = explode ( "(" , $actionArr_prepare [ $i -1]); $actionVal = new UriTemplateActionBuilder( 'u' , $data ); } elseif (preg_match( '/^c\(/' , $actionArr_prepare [ $i -1])){ list( $ac , $data ) = explode ( "(" , $actionArr_prepare [ $i -1]); } elseif (preg_match( '/^cs\(/' , $actionArr_prepare [ $i -1])){ list( $ac , $data ) = explode ( "(" , $actionArr_prepare [ $i -1]); } elseif (preg_match( '/^cm\(/' , $actionArr_prepare [ $i -1])){ list( $ac , $data ) = explode ( "(" , $actionArr_prepare [ $i -1]); } elseif (preg_match( '/^l\(/' , $actionArr_prepare [ $i -1])){ list( $ac , $data ) = explode ( "(" , $actionArr_prepare [ $i -1]); } elseif (preg_match( '/^d\(/' , $actionArr_prepare [ $i -1])){ list( $ac , $data ) = explode ( "(" , $actionArr_prepare [ $i -1]); $actionVal = new DatetimePickerTemplateActionBuilder( 'd' , $data , 'datetime' ); } elseif (preg_match( '/^n\(/' , $actionArr_prepare [ $i -1])){ $actionVal = NULL; continue ; } else { $actionVal = NULL; continue ; } $patternLetter = $Area_arr [ $i -1]; array_push ( $dataArr , new RichMenuAreaBuilder( new RichMenuAreaBoundsBuilder(... $areaBound_arr [ $patternLetter ]), $actionVal ) ); } return $dataArr ; } // $arrayRichMenu = makeFRM(); // $sizeBuilder, $selected, $name, $chatBarText, $areaBuilders // 1686, 843. // 2500 // ($x, $y, $width, $height) $_idRichMenu = $imgTypePattern . "-" . $numberID ; $respRichMenu = $bot ->createRichMenu( new RichMenuBuilder( new RichMenuSizeBuilder(1686,2500),true, "Rich Menu $_idRichMenu" , "เมนู" , makeFRM( $imgTypePattern ) ) ); // ทำอื่นๆ $textReplyMessage = " การสร้าง Rich Menu " . $respRichMenu ->getRawBody(). " Res = " .json_encode( $dataArr ); $replyData = new TextMessageBuilder( $textReplyMessage ); break ; case "gr-" : $result = json_decode( $respRichMenu ->getRawBody(),TRUE); $defaultRichMenu = (isset( $result [ 'richMenuId' ]))? $result [ 'richMenuId' ]:NULL; $respRichMenu = $bot ->getRichMenuList(); $result = json_decode( $respRichMenu ->getRawBody(),TRUE); // สร้างตัวแปร สำหรับเก็บ rich menu แต่ละรายการไว้ในแต่ละคอลัมน์ $columnTemplate = array (); foreach ( $result [ 'richmenus' ] as $itemRichMenu ){ $_txtShow = ( $itemRichMenu [ 'richMenuId' ]== $defaultRichMenu )? "ยกเลิก" : "กำหนดเป็น" ; $_action = ( $itemRichMenu [ 'richMenuId' ]== $defaultRichMenu )? "c_default_richmenu" : "s_default_richmenu" ; $imgRichLayout = substr ( str_replace ( 'Rich Menu ' , '' , $itemRichMenu [ 'name' ]),0,1); array_push ( $columnTemplate , new CarouselColumnTemplateBuilder( $itemRichMenu [ 'name' ], // ชื่อ rich menu 'เลือกการจัดการ' , 'https://www.example.com/bot/rich-menu/rich-menu-pattern-0' . $imgRichLayout . '.png' , // ไม่แสดงรูป มีมี url รูป array ( new PostbackTemplateActionBuilder( $_txtShow . ' Default' , // ข้อความแสดงในปุ่ม http_build_query( array ( 'action' => $_action , 'richMenuName' => $itemRichMenu [ 'name' ], 'richMenuId' => $itemRichMenu [ 'richMenuId' ] )), // ข้อมูลที่จะส่งไปใน webhook ผ่าน postback event 'กำหนด Default Rich Menu' // ข้อความที่จะแสดงฝั่งผู้ใช้ เมื่อคลิกเลือก ), new PostbackTemplateActionBuilder( 'แสดงที่ Default' , // ข้อความแสดงในปุ่ม http_build_query( array ( 'action' => 'g_default_richmenu' , 'richMenuName' => $itemRichMenu [ 'name' ], 'richMenuId' => $itemRichMenu [ 'richMenuId' ] )), // ข้อมูลที่จะส่งไปใน webhook ผ่าน postback event 'แสดง Default Rich Menu' // ข้อความที่จะแสดงฝั่งผู้ใช้ เมื่อคลิกเลือก ), new PostbackTemplateActionBuilder( 'อัพโหลดรูป Rich Menu นี้' , // ข้อความแสดงในปุ่ม http_build_query( array ( 'action' => 'upload_richmenu' , 'richMenuName' => $itemRichMenu [ 'name' ], 'richMenuId' => $itemRichMenu [ 'richMenuId' ] )), // ข้อมูลที่จะส่งไปใน webhook ผ่าน postback event 'อัพโหลดรูป Rich Menu' // ข้อความที่จะแสดงฝั่งผู้ใช้ เมื่อคลิกเลือก ) ) ) // end CarouselColumnTemplateBuilder ); // end array push function } // end foreach // ใช้ Carousel Template วนลูปแสดงรายการ rich menu ที่ได้สร้างไว้ $replyData = new TemplateMessageBuilder( 'Carousel' , new CarouselTemplateBuilder( $columnTemplate ) ); break ; case "gr2-" : $respRichMenu = $bot ->getRichMenuList(); $result = json_decode( $respRichMenu ->getRawBody(),TRUE); // สร้างตัวแปร สำหรับเก็บ rich menu แต่ละรายการไว้ในแต่ละคอลัมน์ $columnTemplate = array (); foreach ( $result [ 'richmenus' ] as $itemRichMenu ){ $imgRichLayout = substr ( str_replace ( 'Rich Menu ' , '' , $itemRichMenu [ 'name' ]),0,1); array_push ( $columnTemplate , new CarouselColumnTemplateBuilder( $itemRichMenu [ 'name' ], // ชื่อ rich menu 'เลือกการจัดการ' , 'https://www.example.com/bot/rich-menu/rich-menu-pattern-0' . $imgRichLayout . '.png' , // ไม่แสดงรูป มีมี url รูป array ( new PostbackTemplateActionBuilder( 'รายละเอียด Rich Menu' , // ข้อความแสดงในปุ่ม http_build_query( array ( 'action' => 'get_richmenu' , 'richMenuName' => $itemRichMenu [ 'name' ], 'richMenuId' => $itemRichMenu [ 'richMenuId' ] )), // ข้อมูลที่จะส่งไปใน webhook ผ่าน postback event 'ข้อมูล Rich Menu' // ข้อความที่จะแสดงฝั่งผู้ใช้ เมื่อคลิกเลือก ), new PostbackTemplateActionBuilder( 'ลบ Rich Menu นี้' , // ข้อความแสดงในปุ่ม http_build_query( array ( 'action' => 'delete_richmenu' , 'richMenuName' => $itemRichMenu [ 'name' ], 'richMenuId' => $itemRichMenu [ 'richMenuId' ] )), // ข้อมูลที่จะส่งไปใน webhook ผ่าน postback event 'ลบ Rich Menu' // ข้อความที่จะแสดงฝั่งผู้ใช้ เมื่อคลิกเลือก ), new PostbackTemplateActionBuilder( 'อัพโหลดรูป Rich Menu นี้' , // ข้อความแสดงในปุ่ม http_build_query( array ( 'action' => 'upload_richmenu' , 'richMenuName' => $itemRichMenu [ 'name' ], 'richMenuId' => $itemRichMenu [ 'richMenuId' ] )), // ข้อมูลที่จะส่งไปใน webhook ผ่าน postback event 'อัพโหลดรูป Rich Menu' // ข้อความที่จะแสดงฝั่งผู้ใช้ เมื่อคลิกเลือก ) ) ) // end CarouselColumnTemplateBuilder ); // end array push function } // end foreach // ใช้ Carousel Template วนลูปแสดงรายการ rich menu ที่ได้สร้างไว้ $replyData = new TemplateMessageBuilder( 'Carousel' , new CarouselTemplateBuilder( $columnTemplate ) ); break ; case "ot" : // ทำอื่นๆ break ; case "l" : // เงื่อนไขทดสอบถ้ามีใครพิมพ์ L ใน GROUP / ROOM แล้วให้ bot ออกจาก GROUP / ROOM $sourceId = $eventObj ->getEventSourceId(); if ( $eventObj ->isGroupEvent()){ $bot ->leaveGroup( $sourceId ); } if ( $eventObj ->isRoomEvent()){ $bot ->leaveRoom( $sourceId ); } break ; case "qr" : $postback = new PostbackTemplateActionBuilder( 'Postback' , // ข้อความแสดงในปุ่ม http_build_query( array ( 'action' => 'buy' , 'item' =>100 )), // ข้อมูลที่จะส่งไปใน webhook ผ่าน postback event 'Buy' // ข้อความที่จะแสดงฝั่งผู้ใช้ เมื่อคลิกเลือก ); $txtMsg = new MessageTemplateActionBuilder( 'ข้อความภาษาไทย' , // ข้อความแสดงในปุ่ม 'thai' // ข้อความที่จะแสดงฝั่งผู้ใช้ เมื่อคลิกเลือก ); $datetimePicker = new DatetimePickerTemplateActionBuilder( 'Datetime Picker' , // ข้อความแสดงในปุ่ม http_build_query( array ( 'action' => 'reservation' , 'person' =>5 )), // ข้อมูลที่จะส่งไปใน webhook ผ่าน postback event 'datetime' , // date | time | datetime รูปแบบข้อมูลที่จะส่ง ในที่นี้ใช้ datatime substr_replace( date ( "Y-m-d H:i" ), 'T' ,10,1), // วันที่ เวลา ค่าเริ่มต้นที่ถูกเลือก substr_replace( date ( "Y-m-d H:i" , strtotime ( "+5 day" )), 'T' ,10,1), //วันที่ เวลา มากสุดที่เลือกได้ substr_replace( date ( "Y-m-d H:i" ), 'T' ,10,1) //วันที่ เวลา น้อยสุดที่เลือกได้ ); $quickReply = new QuickReplyMessageBuilder( array ( new QuickReplyButtonBuilder( new LocationTemplateActionBuilder( 'เลือกตำแหน่ง' )), new QuickReplyButtonBuilder( new CameraTemplateActionBuilder( 'ถ่ายรูป' )), new QuickReplyButtonBuilder( new CameraRollTemplateActionBuilder( 'เลือกรูปภาพ' )), new QuickReplyButtonBuilder( $postback ), new QuickReplyButtonBuilder( $datetimePicker ), new QuickReplyButtonBuilder( $txtMsg , ), ) ); $textReplyMessage = "ส่งพร้อม quick reply " ; $replyData = new TextMessageBuilder( $textReplyMessage , $quickReply ); break ; default : $textReplyMessage = " คุณไม่ได้พิมพ์ ค่า ตามที่กำหนด" ; $replyData = new TextMessageBuilder( $textReplyMessage ); break ; } break ; default : if (! is_null ( $replyData )){ } else { // กรณีทดสอบเงื่อนไขอื่นๆ ผู้ใช้ไม่ได้ส่งเป็นข้อความ $textReplyMessage = 'สวัสดีครับ คุณ ' . $typeMessage ; $replyData = new TextMessageBuilder( $textReplyMessage ); } break ; } } } ?> |
ไฟล์ข้างต้น เราจะรองรับคำสั่งเมื่อพิมพ์ liff> เข้าไป แล้วทำการแสดง LIFF Manager
ซึ่งเป็น Flex Message ที่เราจะใช้ในการจัดการรายการ LIFF app ตัวอย่างผลลัพธ์ ดังรูปด้านล่าง

การทำงานก็คือ ถ้าเรากดที่ชื่อ LIFF app ก็จะทำการเรียก LIFF app นั้นๆ มาแสดง แต่ถ้าเรากดคำว่า Edit
ก็จะส่ง liffid ไปดึงข้อมูลมาแสดงให้หน้า LIFF app Manager ที่เรากำลังจะทำ ถ้ายังไม่มีค่านี้ ให้ปล่อยว่า
ไว้ก่อน ค่อยเอาค่ามาใส่หลังจากสร้างแล้วก็ได้
1 |
ต่อไปเราสร้างไฟล์ liff.php สำหรับ web app จัดการ LIFF โดยใช้รูปแบบไฟล์ PHP
ไว้ใน path ตามโครงสร้างโฟลเดอร์ดังรูปด้านล่าง
>bot
> bot.php
> bot_action.php
>bot
>liff
>app1
|---> liff.php
|---> liff_ajax.php
|---> liff_drawing.php
ไฟล์ liff.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 | <?php // กรณีต้องการตรวจสอบการแจ้ง error ให้เปิด 3 บรรทัดล่างนี้ให้ทำงาน กรณีไม่ ให้ comment ปิดไป ini_set ( 'display_errors' , 1); ini_set ( 'display_startup_errors' , 1); error_reporting (E_ALL); // include composer autoload require_once '../../../vendor/autoload.php' ; // การตั้งเกี่ยวกับ bot require_once '../../bot_settings.php' ; // กรณีมีการเชื่อมต่อกับฐานข้อมูล //require_once("dbconnect.php"); ///////////// ส่วนของการเรียกใช้งาน class ผ่าน namespace use LINE\LINEBot; use LINE\LINEBot\HTTPClient; use LINE\LINEBot\HTTPClient\CurlHTTPClient; use LINE\LINEBot\Event; use LINE\LINEBot\Event\BaseEvent; use LINE\LINEBot\Event\MessageEvent; use LINE\LINEBot\Event\AccountLinkEvent; use LINE\LINEBot\Event\MemberJoinEvent; use LINE\LINEBot\MessageBuilder; use LINE\LINEBot\MessageBuilder\TextMessageBuilder; use LINE\LINEBot\MessageBuilder\StickerMessageBuilder; use LINE\LINEBot\MessageBuilder\ImageMessageBuilder; use LINE\LINEBot\MessageBuilder\LocationMessageBuilder; use LINE\LINEBot\MessageBuilder\AudioMessageBuilder; use LINE\LINEBot\MessageBuilder\VideoMessageBuilder; use LINE\LINEBot\ImagemapActionBuilder; use LINE\LINEBot\ImagemapActionBuilder\AreaBuilder; use LINE\LINEBot\ImagemapActionBuilder\ImagemapMessageActionBuilder ; use LINE\LINEBot\ImagemapActionBuilder\ImagemapUriActionBuilder; use LINE\LINEBot\MessageBuilder\Imagemap\BaseSizeBuilder; use LINE\LINEBot\MessageBuilder\ImagemapMessageBuilder; use LINE\LINEBot\MessageBuilder\MultiMessageBuilder; use LINE\LINEBot\TemplateActionBuilder; use LINE\LINEBot\TemplateActionBuilder\DatetimePickerTemplateActionBuilder; use LINE\LINEBot\TemplateActionBuilder\MessageTemplateActionBuilder; use LINE\LINEBot\TemplateActionBuilder\PostbackTemplateActionBuilder; use LINE\LINEBot\TemplateActionBuilder\UriTemplateActionBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder; use LINE\LINEBot\MessageBuilder\TemplateMessageBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder\ButtonTemplateBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder\CarouselTemplateBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder\CarouselColumnTemplateBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder\ConfirmTemplateBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder\ImageCarouselTemplateBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder\ImageCarouselColumnTemplateBuilder; use LINE\LINEBot\QuickReplyBuilder; use LINE\LINEBot\QuickReplyBuilder\QuickReplyMessageBuilder; use LINE\LINEBot\QuickReplyBuilder\ButtonBuilder\QuickReplyButtonBuilder; use LINE\LINEBot\TemplateActionBuilder\CameraRollTemplateActionBuilder; use LINE\LINEBot\TemplateActionBuilder\CameraTemplateActionBuilder; use LINE\LINEBot\TemplateActionBuilder\LocationTemplateActionBuilder; use LINE\LINEBot\RichMenuBuilder; use LINE\LINEBot\RichMenuBuilder\RichMenuSizeBuilder; use LINE\LINEBot\RichMenuBuilder\RichMenuAreaBuilder; use LINE\LINEBot\RichMenuBuilder\RichMenuAreaBoundsBuilder; use LINE\LINEBot\Constant\Flex\ComponentIconSize; use LINE\LINEBot\Constant\Flex\ComponentImageSize; use LINE\LINEBot\Constant\Flex\ComponentImageAspectRatio; use LINE\LINEBot\Constant\Flex\ComponentImageAspectMode; use LINE\LINEBot\Constant\Flex\ComponentFontSize; use LINE\LINEBot\Constant\Flex\ComponentFontWeight; use LINE\LINEBot\Constant\Flex\ComponentMargin; use LINE\LINEBot\Constant\Flex\ComponentSpacing; use LINE\LINEBot\Constant\Flex\ComponentButtonStyle; use LINE\LINEBot\Constant\Flex\ComponentButtonHeight; use LINE\LINEBot\Constant\Flex\ComponentSpaceSize; use LINE\LINEBot\Constant\Flex\ComponentGravity; use LINE\LINEBot\MessageBuilder\FlexMessageBuilder; use LINE\LINEBot\MessageBuilder\Flex\BubbleStylesBuilder; use LINE\LINEBot\MessageBuilder\Flex\BlockStyleBuilder; use LINE\LINEBot\MessageBuilder\Flex\ContainerBuilder\BubbleContainerBuilder; use LINE\LINEBot\MessageBuilder\Flex\ContainerBuilder\CarouselContainerBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\BoxComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\ButtonComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\IconComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\ImageComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\SpacerComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\FillerComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\SeparatorComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\TextComponentBuilder; use LINE\LINEBot\Response; // สร้าง class เพิ่ม โดย extents จาก ตัวเดิม เพื่อที่จะเพิ่ม ฟังก์ชั่น put() เพื่อใช้ในการอัพเดท LIFF class CurlHTTPClientEx extends CurlHTTPClient { public function put( $url , array $data , array $headers = null) { $curl = curl_init(); curl_setopt_array( $curl , array ( CURLOPT_URL => $url , CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => "PUT" , CURLOPT_POSTFIELDS => json_encode( $data ), CURLOPT_BINARYTRANSFER => true, CURLOPT_HEADER => true, CURLOPT_HTTPHEADER => array ( "Authorization: Bearer " .LINE_MESSAGE_ACCESS_TOKEN, "Content-Type: application/json" , "charset: utf-8" ), )); $result = curl_exec( $curl ); if (curl_errno( $curl )) { throw new CurlExecutionException(curl_error( $curl )); } $info = curl_getinfo( $curl ); $httpStatus = $info [ 'http_code' ]; $responseHeaderSize = $info [ 'header_size' ]; $responseHeaderStr = substr ( $result , 0, $responseHeaderSize ); $responseHeaders = []; foreach ( explode ( "\r\n" , $responseHeaderStr ) as $responseHeader ) { $kv = explode ( ':' , $responseHeader , 2); if ( count ( $kv ) === 2) { $responseHeaders [ $kv [0]] = trim( $kv [1]); } } $body = substr ( $result , $responseHeaderSize ); if (isset( $options [CURLOPT_INFILE])) { fclose( $options [CURLOPT_INFILE]); } return new Response( $httpStatus , $body , $responseHeaders ); } } $httpClient = new CurlHTTPClientEx(LINE_MESSAGE_ACCESS_TOKEN); $bot = new LINEBot( $httpClient , array ( 'channelSecret' => LINE_MESSAGE_CHANNEL_SECRET)); ?> <!doctype html> <html> <head> <meta charset= "utf-8" > <meta name= "viewport" content= "width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no" > <title><?=(isset( $_GET [ 'section' ]) && $_GET [ 'section' ]== "edit" )? "Edit" : "Add" ?> LIFF</title> <link rel= "stylesheet" href= "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.1/css/all.min.css" > </head> <body class = "bg-light" > <?php // ตัวแปรสถานะการ เพิ่ม ลบ และ แก้ไข $status_edit = NULL; $status_add = NULL; $status_delete = NULL; // ค่าเริ่มต้น ของข้อมูล LIFF $arr_Default = array ( "liffId" => "" , "view" => array ( "type" => "full" , ), "description" => "" , "features" => array ( "ble" =>false ) ); // ถ้ามีการส่งข้อมูลจากฟอรฺ์ม if (isset( $_POST [ 'btnConfirm' ])){ // จัดรูปแบบ array ของข้อมูล โดยใช้ค่าจากฟอร์ม $arr_data = array ( "view" => array ( "type" => $_POST [ 'LiffSize' ], "url" =>trim( $_POST [ 'AppUrl' ]) ), "description" =>trim( $_POST [ 'LiffName' ]), "features" => array ( "ble" =>(isset( $_POST [ 'LiffBle' ]) && $_POST [ 'LiffBle' ]==1)?true:false ) ); // ถ้ามีตัวแปร $_POST['h_liffid'] แสดงว่าเป็นการแก้ไข if (isset( $_POST [ 'h_liffid' ]) && $_POST [ 'h_liffid' ]!= "" ){ // ถ้ามีการติ้กเลือก เพื่อลบ if (isset( $_POST [ 'LiffDelete' ]) && $_POST [ 'LiffDelete' ]!= "" ){ // ทำการลบข้อมูล $status_delete = true; } else { // ทำการแก้ไขข้อมูล $respLIFF = $httpClient ->put( "https://api.line.me/liff/v1/apps/" .trim( $_POST [ 'h_liffid' ]), $arr_data ); $status_edit = true; } } else { // ทำการเพิ่มข้อมูล $status_add = true; } $resultListLIFF = json_decode( $respLIFF ->getRawBody(),TRUE); } // ดึงรายการ LIFF app ทั้งหมดที่สร้างวไ้ $resultListLIFF = json_decode( $respLIFF ->getRawBody(),TRUE); // ปรับอยู่ในรูปตัวแปร array $arr_LiffData = $arr_Default ; // กำหนดค่าข้อมูลที่จะแสดงในฟอรฺ์ม เป็นค่าเริ่มต้นก่อน if (isset( $_GET [ 'liffid' ])){ // ถ้ามีการส่งค่าเข้ามา // นำค่า liffid ที่ส่งเข้ามา ไปค้นหาใน arrary ของรายการ LIFF ทั้งหมด $keyLIFF = array_search (trim( $_GET [ 'liffid' ]),array_column( $resultListLIFF [ 'apps' ], 'liffId' )); if ( is_int ( $keyLIFF )){ // ถ้ามีรายการที่ตรง // กำหนด รายการ LIFF ที่จะแสดงในฟอร์ม เป็นค่าที่สิ่งขึ้นมา $arr_LiffData = array_merge ( $arr_Default , $resultListLIFF [ 'apps' ][ $keyLIFF ]); } } ?> <?php // กำหนดค่าให้ Size และ BLE เพื่อนำปใช้ในการแสดงผลในฟอร์ม $dataSize = $arr_LiffData [ 'view' ][ 'type' ]; $dataBle = $arr_LiffData [ 'features' ][ 'ble' ];; ?> <div class = "container bg-light" > <form id= "myform1" name= "form1" method= "post" action= "" > <?php // แสดง LIFF app URL ถ้าเป็นการแก้ไข if (isset( $_GET [ 'section' ])== "edit" ){ ?> <div class = "form-group row mb-0 pb-3 border-bottom" > <label for = "LiffUrl" class = "col-sm-3 col-form-label text-left font-weight-bold" >LIFF URL</label> <div class = "col" > <div class = "input-group" > <div class = "input-group-prepend" > <div class = "input-group-text" id= "btnCopy" ><i class = "fas fa-copy" ></i></div> </div> <input type= "text" class = "form-control bg-white" name= "LiffUrl" id= "LiffUrl" value= "line://app/<?=$arr_LiffData['liffId']?>" readonly> </div> </div> </div> <?php } ?> <div class = "form-group row mb-0 pb-2" > <label for = "LiffName" class = "col-sm-3 col-form-label text-left font-weight-bold" >Name</label> <div class = "col" > <input type= "text" class = "form-control bg-white" name= "LiffName" id= "LiffName" autocomplete= "off" value= "<?=$arr_LiffData['description']?>" required> </div> </div> <div class = "form-group row mb-0 pb-2" > <label for = "AppUrl" class = "col-sm-3 col-form-label text-left font-weight-bold" >Endpoint URL</label> <div class = "col" > <input type= "url" class = "form-control bg-white" name= "AppUrl" id= "AppUrl" </div> </div> <div class = "form-group row mb-0 pb-2" > <label for = "LiffSize" class = "col-sm-3 col-form-label text-left font-weight-bold" >Size</label> <div class = "col" > <div class = "btn-group-toggle flex-row " data-toggle= "buttons" > <label class = "btn btn-sm col-3 shadow-sm btn-c-topup btn-light <?=($dataSize==" full ")?" active ":" "?>" > <input type= "radio" name= "LiffSize" autocomplete= "off" value= "full" <?=( $dataSize == "full" )? "checked" : "" ?> required > Full </label> <label class = "btn btn-sm col-3 shadow-sm btn-c-topup btn-light <?=($dataSize==" tall ")?" active ":" "?>" > <input type= "radio" name= "LiffSize" autocomplete= "off" value= "tall" <?=( $dataSize == "tall" )? "checked" : "" ?> required > Tall </label> <label class = "btn btn-sm col-3 shadow-sm btn-c-topup btn-light <?=($dataSize==" compact ")?" active ":" "?>" > <input type= "radio" name= "LiffSize" autocomplete= "off" value= "compact" <?=( $dataSize == "compact" )? "checked" : "" ?> required > Compact </label> </div> </div> </div> <div class = "form-group row mb-0 pb-3 border-bottom" > <label for = "LiffBle" class = "col-sm-3 col-form-label text-left font-weight-bold" >BLE feature</label> <div class = "col" > <div class = "btn-group-toggle" data-toggle= "buttons" > <label class = "btn btn-sm col-3 shadow-sm btn-c-topup btn-light <?=($dataBle==1)?" active ":" "?>" > <input type= "radio" name= "LiffBle" autocomplete= "off" value= "1" <?=( $dataBle ==1)? "checked" : "" ?> required > ON </label> <label class = "btn btn-sm col-3 shadow-sm btn-c-topup btn-light <?=($dataBle==0)?" active ":" "?>" > <input type= "radio" name= "LiffBle" autocomplete= "off" value= "0" <?=( $dataBle ==0)? "checked" : "" ?> required > OFF </label> </div> </div> </div> <?php // แสดงปุ่มสำหรับลบ ถ้าเป็นการแก้ไข if (isset( $_GET [ 'section' ])== "edit" ){ ?> <div class = "form-group row mb-0 pb-4" > <label for = "LiffBle" class = "col-sm-3 col-form-label text-right font-weight-bold text-danger" >Danger Zone</label> <div class = "col text-right" > <div class = "btn-group-toggle" data-toggle= "buttons" > <label class = "btn btn-sm col-3 shadow-sm btn-c-topup btn-light " > <input type= "checkbox" name= "LiffDelete" autocomplete= "off" value= "<?=$_GET['liffid']?>" > <i class = "fas fa-trash-alt" ></i> Delete </label> </div> </div> </div> <?php } ?> <div class = "form-group row mb-0 bg-light py-3 px-2 shadow-sm border-top fixed-bottom" > <div class = "col-6" > <button type= "button" name= "btnCancel" id= "btnCancel" value= "1" class = "btn btn-light bg-white btn-block shadow-sm" >Cancel</button> </div> <div class = "col-6" > <?php // แสด input hidden ถ้าแสดงหน้าต่างแก้ไข if (isset( $_GET [ 'section' ]) && $_GET [ 'section' ]== "edit" ){ ?> <input type= "hidden" name= "h_liffid" value= "<?=$_GET['liffid']?>" /> <?php } ?> <button type= "submit" name= "btnConfirm" id= "btnConfirm" value= "1" class = "btn btn-primary btn-block shadow-sm" >Confirm</button> </div> </div> </form> </div> <script type= "text/javascript" > $( function (){ // ทำคัส่ง copy LIFF app URL $( "#btnCopy" ).on( "click" , function (){ $( "#LiffUrl" ).select(); document.execCommand( "copy" ); }); liff.init( function (data) { // คำสั่ง init() คืนค่าข้อมูลของ LIFF app }); // คำสิ่งปิดหน้า LIFF app view $( "#btnCancel" ).on( "click" , function (){ liff.closeWindow(); }); <?php // ส่งข้อความ liff> เพื่อแสดงรายการ liff อีกครั้ง เมื่อมีการเพิ่ม ลบ หรือแก้ไข รายการ liff if (! is_null ( $status_add ) || ! is_null ( $status_edit ) || ! is_null ( $status_delete )){ ?> setTimeout( function (){ liff.sendMessages([{ type: 'text' , text: "liff>" }]).then( function () { window.alert( "ทำรายการเสร็จสิ้น" ); liff.closeWindow(); }). catch ( function (error) { window.alert( "Error sending message: " + error); liff.closeWindow(); }); },100); <?php } ?> $(document.body).on( "change" , "[name='LiffDelete']" , function (){ $(this).parent( "label" ).toggleClass( "btn-light" ).toggleClass( "btn-danger" ); }); }); </script> </body> </html> |
ตอนนี้เราได้ web app สำหรับจัดการ LIFF ที่ url
https://www.example.com/bot/liff/app1/liff.php
เมื่อได้เรา web app สำหรับจัดการ LIFF app แล้ว ให้เราเข้าไปเพิ่ม LIFF app ใน หน้า console
เพิ่อจะได้นำค่า LIFF URL นี้ไปกำหนดใน bot_action.php

กรอกข้อมูล แล้วกด Confirm

นำค่า LIFF URL ที่ได้ ไปกำหนดในตัวแปร $LIFFappManagerURL ในไฟล์ bot_action.php
ทดสอบเรียกใช้งานผ่าน bot โดยใช้คำสั่ง liff> จะได้ผลลัพธ์ตามรูปด้านล่าง

จะแสดง Flex Message รายการ LIFF Manager ที่เราสามารถ กดแก้ไข หรือเพิ่มรายการ ผ่านหน้า Chat โดยไม่ต้องกลับ
ไปจัดการที่หน้า console อีก เราสามารถทดสอบ เพิ่ม ลบ แก้ไข รายการ ดูได้ที่ตัวอย่างวิดีโอ Demo 1
จากการทพสอบใช้งาน จะพบว่า web app ในรูปแบบ PHP ลักษณะจะเหมือนเราเปิดหน้าบราวเซอร์ และทำรายการผ่าน
เว็บไซต์ทั่วไป บางครั้งก็มีโหลดช้าบ้างเร็วบ้าง เพราะมีการโหลดหน้าเพจทุกครั้งที่ทำรายการ จึงมาเป็นแนวทาง
ในการสร้าง LIFF app ในรูปแบบ ajax ของตัวอย่างที่สอง
LINE LIFF app Manager (Ajax)
การสร้างหน้า web app เพื่อรองรับการใช้งาน ajax จำเป็นอย่างยิ่งที่เราต้องเข้าใจ การจัดการเกี่ยวกับ DOM
Object หรือ Element ต่างๆ ของ HTML ด้วย JavaScript ในที่นี้เราใช้งานร่วมกับ jQuery ทำให้การจัดการไม่ยาก
นัก web app ในรูปแบบ ajax จะทำให้การแสดงผลดูเหมือน mobile app มากกว่าเดิม เพราะจะไม่มีการโหลดหน้า
web app ทั้งหมดใหม่ทุกๆ ครั้งที่มีการเพิ่ม ลบ หรือแก้ไขข้อมูล ทำให้หน้า web app ทำงานเร็วขึ้น
การส่งข้อมูล เพื่อไปทำการ เพิ่ม ลบ แก้ไข ในที่นี้ เราจะแยกไฟล์จัดการกับ Server API ของ LIFF SDK อีกไฟล์
ชื่อว่า liffsdk.php และไฟล์หน้า LIFF app ชื่อ life_ajax.php ดังรายละเอียดโค้ดดังต่อไปนี้
ไฟล์ liff_ajax.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | <!doctype html> <html> <head> <meta charset= "utf-8" > <meta name= "viewport" content= "width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no" > <title></title> <link rel= "stylesheet" href= "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.1/css/all.min.css" > </head> <body class = "bg-light" > <div class = "container bg-light" > <form id= "myform1" name= "form1" method= "post" action= "" > <div class = "form-group row mb-0 pb-3 border-bottom d-none" > <label for = "LiffUrl" class = "col-sm-3 col-form-label text-left font-weight-bold" >LIFF URL</label> <div class = "col" > <div class = "input-group" > <div class = "input-group-prepend" > <div class = "input-group-text" id= "btnCopy" ><i class = "fas fa-copy" ></i></div> </div> <input type= "text" class = "form-control bg-white" name= "LiffUrl" id= "LiffUrl" value= "" readonly> </div> </div> </div> <div class = "form-group row mb-0 pb-2" > <label for = "LiffName" class = "col-sm-3 col-form-label text-left font-weight-bold" >Name</label> <div class = "col" > <input type= "text" class = "form-control bg-white" name= "LiffName" id= "LiffName" autocomplete= "off" value= "" required> </div> </div> <div class = "form-group row mb-0 pb-2" > <label for = "AppUrl" class = "col-sm-3 col-form-label text-left font-weight-bold" >Endpoint URL</label> <div class = "col" > <input type= "url" class = "form-control bg-white" name= "AppUrl" id= "AppUrl" </div> </div> <div class = "form-group row mb-0 pb-2" > <label for = "LiffSize" class = "col-sm-3 col-form-label text-left font-weight-bold" >Size</label> <div class = "col" > <div class = "btn-group-toggle flex-row " data-toggle= "buttons" > <label class = "btn btn-sm col-3 shadow-sm btn-c-topup btn-light" > <input type= "radio" name= "LiffSize" autocomplete= "off" value= "full" required > Full </label> <label class = "btn btn-sm col-3 shadow-sm btn-c-topup btn-light" > <input type= "radio" name= "LiffSize" autocomplete= "off" value= "tall" required > Tall </label> <label class = "btn btn-sm col-3 shadow-sm btn-c-topup btn-light" > <input type= "radio" name= "LiffSize" autocomplete= "off" value= "compact" required > Compact </label> </div> </div> </div> <div class = "form-group row mb-0 pb-3 border-bottom" > <label for = "LiffBle" class = "col-sm-3 col-form-label text-left font-weight-bold" >BLE feature</label> <div class = "col" > <div class = "btn-group-toggle" data-toggle= "buttons" > <label class = "btn btn-sm col-3 shadow-sm btn-c-topup btn-light" > <input type= "radio" name= "LiffBle" autocomplete= "off" value= "1" required > ON </label> <label class = "btn btn-sm col-3 shadow-sm btn-c-topup btn-light" > <input type= "radio" name= "LiffBle" autocomplete= "off" value= "0" required > OFF </label> </div> </div> </div> <div class = "form-group row mb-0 pb-4 d-none" > <label for = "LiffBle" class = "col-sm-3 col-form-label text-right font-weight-bold text-danger" >Danger Zone</label> <div class = "col text-right" > <div class = "btn-group-toggle" data-toggle= "buttons" > <label class = "btn btn-sm col-3 shadow-sm btn-c-topup btn-light " > <input type= "checkbox" name= "LiffDelete" autocomplete= "off" value= "" > <i class = "fas fa-trash-alt" ></i> Delete </label> </div> </div> </div> <div class = "form-group row mb-0 bg-light py-3 px-2 shadow-sm border-top fixed-bottom" > <div class = "col-6" > <button type= "button" name= "btnCancel" id= "btnCancel" value= "1" class = "btn btn-light bg-white btn-block shadow-sm" >Cancel</button> </div> <div class = "col-6" > <input type= "hidden" name= "h_liffid" value= "" disabled /> <button type= "submit" name= "btnConfirm" id= "btnConfirm" value= "1" class = "btn btn-primary btn-block shadow-sm" >Confirm</button> </div> </div> </form> </div> <script type= "text/javascript" > $( function (){ // ฟังก์ชั่น javascript สำหรับดึวตัวแปร ที่ส่งมาใน url var _get = function (val){ var result = null; // กำหนดค่าเริ่มต้นผลลัพธ์ tmp = []; // กำหนดตัวแปรเก็บค่า เป็น array // เก็บค่า url โดยตัด ? อันแรกออก แล้วแยกโดยตัวแบ่ง & var items = location.search. substr (1).split( "&" ); for ( var index = 0; index < items.length; index++) { // วนลูป tmp = items[index].split( "=" ); // แยกระหว่างชื่อตัวแปร และค่าของตัวแปร // ถ้าค่าที่ส่งมาตรวจสอบชื่อตัวแปรตรง ให้เก็บค่าผลัพธ์เป็นค่าของตัวแปรนั้นๆ if (tmp[0] === val) result = decodeURIComponent(tmp[1]); } return result; // คืนค่าของตัวแปรต้องการ ถ้าไม่มีจะเป็น null } // ถ้ามีการส่ง liffid มาใน url if (_get( 'liffid' )){ document.title= "Edit LIFF" ; // กำหนด title เป็น Edit LIFF } else { document.title= "Add LIFF" ; // กำหนด title เป็น Add LIFF } // ทำคำสั่งสำหรับ copy LIFF url $( "#btnCopy" ).on( "click" , function (){ $( "#LiffUrl" ).select(); document.execCommand( "copy" ); }); // เมื่อเปิด LIFF app ขึ้นมา liff.init( function (data) { // คำสั่ง init() คืนค่าข้อมูลของ LIFF app // ดึงข้อมูลจาก ajax ไฟล์ เพื่อนำมาอัพเดทแสดงผลหน้าฟอร์ม $.get( "liffsdk.php" ,{ getLiff:1, liffid:_get( 'liffid' ) }, function (data){ var resp = $.parseJSON(data); // แปลง json string เป็น object if (resp.liffId!= "" ){ // ถ้ามีค่า liffid แสดงว่าเป็นโหมดแก้ไขข้อมูล $( "[name='h_liffid']" ).removeAttr( "disabled" ).val(resp.liffId); $( "[name='LiffUrl']" ).val( "line://app/" +resp.liffId).parents( ".d-none" ).toggleClass( "d-none" ).toggleClass( "d-block" ); $( "[name='LiffDelete']" ).val(resp.liffId).parents( ".d-none" ).toggleClass( "d-none" ).toggleClass( "d-block" ); } $( "[name='AppUrl']" ).val(resp.view.url); $( "[name='LiffName']" ).val(resp.description); $( "[name='LiffSize'][value='" +resp.view.type+ "']" ).prop( "checked" ,true).parent( "label" ).addClass( "active" ); $( "[name='LiffBle'][value='" +(+resp.features.ble)+ "']" ).prop( "checked" ,true).parent( "label" ).addClass( "active" ); }); }); // ทำคำสั่งสำปรับปิดหน้าต่าง LIFF app view $( "#btnCancel" ).on( "click" , function (){ liff.closeWindow(); }); // เมื่อ ส่งข้อมูลในฟอร์มโดยการ submit ใช้รูปแบบการส่งคาแบบ ajax แทนการ submit ปกติ $( "#myform1" ).on( "submit" , function (){ var FormData = $(this).serialize(); // เตรียมข้อมูลในฟอร์มสำหรับส่งค่า FormData += "&btnConfirm=1" ; // ข้อมูลปุ่มกด จะไม่ถูกส่งไปด้วย ต้องต่อค่าเข้าไป $.post( "liffsdk.php" ,FormData, function (data){ // เมื่อส่งข้อมูลไปอัพเดทแล้ว ให้ส่งข้อความ liff> ไปที่ห้องสนทนา เพื่อให้แสดง Flex // ของ LIFF เพื่อจะเห็นรายการที่เพิ่ม ลบ หรืแก้ไข คล้ายการ refresh liff.sendMessages([{ type: 'text' , text: "liff>" }]).then( function () { window.alert( "ทำรายการเสร็จสิ้น" ); liff.closeWindow(); }). catch ( function (error) { window.alert( "Error sending message: " + error); liff.closeWindow(); }); }); return false; // ไม่ให้ submit แบบปกติ ทำงาน }); $(document.body).on( "change" , "[name='LiffDelete']" , function (){ $(this).parent( "label" ).toggleClass( "btn-light" ).toggleClass( "btn-danger" ); }); }); </script> </body> </html> |
ไฟล์ liffsdk.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | <?php // กรณีต้องการตรวจสอบการแจ้ง error ให้เปิด 3 บรรทัดล่างนี้ให้ทำงาน กรณีไม่ ให้ comment ปิดไป ini_set ( 'display_errors' , 1); ini_set ( 'display_startup_errors' , 1); error_reporting (E_ALL); // include composer autoload require_once '../../../vendor/autoload.php' ; // การตั้งเกี่ยวกับ bot require_once '../../bot_settings.php' ; // กรณีมีการเชื่อมต่อกับฐานข้อมูล //require_once("dbconnect.php"); ///////////// ส่วนของการเรียกใช้งาน class ผ่าน namespace use LINE\LINEBot; use LINE\LINEBot\HTTPClient; use LINE\LINEBot\HTTPClient\CurlHTTPClient; use LINE\LINEBot\Event; use LINE\LINEBot\Event\BaseEvent; use LINE\LINEBot\Event\MessageEvent; use LINE\LINEBot\Event\AccountLinkEvent; use LINE\LINEBot\Event\MemberJoinEvent; use LINE\LINEBot\MessageBuilder; use LINE\LINEBot\MessageBuilder\TextMessageBuilder; use LINE\LINEBot\MessageBuilder\StickerMessageBuilder; use LINE\LINEBot\MessageBuilder\ImageMessageBuilder; use LINE\LINEBot\MessageBuilder\LocationMessageBuilder; use LINE\LINEBot\MessageBuilder\AudioMessageBuilder; use LINE\LINEBot\MessageBuilder\VideoMessageBuilder; use LINE\LINEBot\ImagemapActionBuilder; use LINE\LINEBot\ImagemapActionBuilder\AreaBuilder; use LINE\LINEBot\ImagemapActionBuilder\ImagemapMessageActionBuilder ; use LINE\LINEBot\ImagemapActionBuilder\ImagemapUriActionBuilder; use LINE\LINEBot\MessageBuilder\Imagemap\BaseSizeBuilder; use LINE\LINEBot\MessageBuilder\ImagemapMessageBuilder; use LINE\LINEBot\MessageBuilder\MultiMessageBuilder; use LINE\LINEBot\TemplateActionBuilder; use LINE\LINEBot\TemplateActionBuilder\DatetimePickerTemplateActionBuilder; use LINE\LINEBot\TemplateActionBuilder\MessageTemplateActionBuilder; use LINE\LINEBot\TemplateActionBuilder\PostbackTemplateActionBuilder; use LINE\LINEBot\TemplateActionBuilder\UriTemplateActionBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder; use LINE\LINEBot\MessageBuilder\TemplateMessageBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder\ButtonTemplateBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder\CarouselTemplateBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder\CarouselColumnTemplateBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder\ConfirmTemplateBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder\ImageCarouselTemplateBuilder; use LINE\LINEBot\MessageBuilder\TemplateBuilder\ImageCarouselColumnTemplateBuilder; use LINE\LINEBot\QuickReplyBuilder; use LINE\LINEBot\QuickReplyBuilder\QuickReplyMessageBuilder; use LINE\LINEBot\QuickReplyBuilder\ButtonBuilder\QuickReplyButtonBuilder; use LINE\LINEBot\TemplateActionBuilder\CameraRollTemplateActionBuilder; use LINE\LINEBot\TemplateActionBuilder\CameraTemplateActionBuilder; use LINE\LINEBot\TemplateActionBuilder\LocationTemplateActionBuilder; use LINE\LINEBot\RichMenuBuilder; use LINE\LINEBot\RichMenuBuilder\RichMenuSizeBuilder; use LINE\LINEBot\RichMenuBuilder\RichMenuAreaBuilder; use LINE\LINEBot\RichMenuBuilder\RichMenuAreaBoundsBuilder; use LINE\LINEBot\Constant\Flex\ComponentIconSize; use LINE\LINEBot\Constant\Flex\ComponentImageSize; use LINE\LINEBot\Constant\Flex\ComponentImageAspectRatio; use LINE\LINEBot\Constant\Flex\ComponentImageAspectMode; use LINE\LINEBot\Constant\Flex\ComponentFontSize; use LINE\LINEBot\Constant\Flex\ComponentFontWeight; use LINE\LINEBot\Constant\Flex\ComponentMargin; use LINE\LINEBot\Constant\Flex\ComponentSpacing; use LINE\LINEBot\Constant\Flex\ComponentButtonStyle; use LINE\LINEBot\Constant\Flex\ComponentButtonHeight; use LINE\LINEBot\Constant\Flex\ComponentSpaceSize; use LINE\LINEBot\Constant\Flex\ComponentGravity; use LINE\LINEBot\MessageBuilder\FlexMessageBuilder; use LINE\LINEBot\MessageBuilder\Flex\BubbleStylesBuilder; use LINE\LINEBot\MessageBuilder\Flex\BlockStyleBuilder; use LINE\LINEBot\MessageBuilder\Flex\ContainerBuilder\BubbleContainerBuilder; use LINE\LINEBot\MessageBuilder\Flex\ContainerBuilder\CarouselContainerBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\BoxComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\ButtonComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\IconComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\ImageComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\SpacerComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\FillerComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\SeparatorComponentBuilder; use LINE\LINEBot\MessageBuilder\Flex\ComponentBuilder\TextComponentBuilder; use LINE\LINEBot\Response; // สร้าง class เพิ่ม โดย extents จาก ตัวเดิม เพื่อที่จะเพิ่ม ฟังก์ชั่น put() เพื่อใช้ในการอัพเดท LIFF class CurlHTTPClientEx extends CurlHTTPClient { public function put( $url , array $data , array $headers = null) { $curl = curl_init(); curl_setopt_array( $curl , array ( CURLOPT_URL => $url , CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => "PUT" , CURLOPT_POSTFIELDS => json_encode( $data ), CURLOPT_BINARYTRANSFER => true, CURLOPT_HEADER => true, CURLOPT_HTTPHEADER => array ( "Authorization: Bearer " .LINE_MESSAGE_ACCESS_TOKEN, "Content-Type: application/json" , "charset: utf-8" ), )); $result = curl_exec( $curl ); if (curl_errno( $curl )) { throw new CurlExecutionException(curl_error( $curl )); } $info = curl_getinfo( $curl ); $httpStatus = $info [ 'http_code' ]; $responseHeaderSize = $info [ 'header_size' ]; $responseHeaderStr = substr ( $result , 0, $responseHeaderSize ); $responseHeaders = []; foreach ( explode ( "\r\n" , $responseHeaderStr ) as $responseHeader ) { $kv = explode ( ':' , $responseHeader , 2); if ( count ( $kv ) === 2) { $responseHeaders [ $kv [0]] = trim( $kv [1]); } } $body = substr ( $result , $responseHeaderSize ); if (isset( $options [CURLOPT_INFILE])) { fclose( $options [CURLOPT_INFILE]); } return new Response( $httpStatus , $body , $responseHeaders ); } } $httpClient = new CurlHTTPClientEx(LINE_MESSAGE_ACCESS_TOKEN); $bot = new LINEBot( $httpClient , array ( 'channelSecret' => LINE_MESSAGE_CHANNEL_SECRET)); // ถ้ามีการส่งข้อมูลจากฟอรฺ์ม if (isset( $_POST [ 'btnConfirm' ])){ // ตัวแปรสถานะการ เพิ่ม ลบ และ แก้ไข $status_edit = NULL; $status_add = NULL; $status_delete = NULL; // จัดรูปแบบ array ของข้อมูล โดยใช้ค่าจากฟอร์ม $arr_data = array ( "view" => array ( "type" => $_POST [ 'LiffSize' ], "url" =>trim( $_POST [ 'AppUrl' ]) ), "description" =>trim( $_POST [ 'LiffName' ]), "features" => array ( "ble" =>(isset( $_POST [ 'LiffBle' ]) && $_POST [ 'LiffBle' ]==1)?true:false ) ); // ถ้ามีตัวแปร $_POST['h_liffid'] แสดงว่าเป็นการแก้ไข if (isset( $_POST [ 'h_liffid' ]) && $_POST [ 'h_liffid' ]!= "" ){ // ถ้ามีการติ้กเลือก เพื่อลบ if (isset( $_POST [ 'LiffDelete' ]) && $_POST [ 'LiffDelete' ]!= "" ){ // ทำการลบข้อมูล $status_delete = true; } else { // ทำการแก้ไขข้อมูล $respLIFF = $httpClient ->put( "https://api.line.me/liff/v1/apps/" .trim( $_POST [ 'h_liffid' ]), $arr_data ); $status_edit = true; } } else { // ทำการเพิ่มข้อมูล $status_add = true; } $resultListLIFF = json_decode( $respLIFF ->getRawBody(),TRUE); echo $respLIFF ->getRawBody(); // ส่งข้อมูล liff app กลับในรูปแบบ json string ไปใช้งานต่อ exit ; } if (isset( $_GET [ 'getLiff' ])){ // ค่าเริ่มต้น ของข้อมูล LIFF $arr_Default = array ( "liffId" => "" , "view" => array ( "type" => "full" , ), "description" => "" , "features" => array ( "ble" =>false ) ); // ดึงรายการ LIFF app ทั้งหมดที่สร้างวไ้ $resultListLIFF = json_decode( $respLIFF ->getRawBody(),TRUE); // ปรับอยู่ในรูปตัวแปร array $arr_LiffData = $arr_Default ; // กำหนดค่าข้อมูลที่จะแสดงในฟอรฺ์ม เป็นค่าเริ่มต้นก่อน if (isset( $_GET [ 'liffid' ]) && $_GET [ 'liffid' ]!= "" ){ // ถ้ามีการส่งค่าเข้ามา // นำค่า liffid ที่ส่งเข้ามา ไปค้นหาใน arrary ของรายการ LIFF ทั้งหมด $keyLIFF = array_search (trim( $_GET [ 'liffid' ]),array_column( $resultListLIFF [ 'apps' ], 'liffId' )); if ( is_int ( $keyLIFF )){ // ถ้ามีรายการที่ตรง // กำหนด รายการ LIFF ที่จะแสดงในฟอร์ม เป็นค่าที่สิ่งขึ้นมา $arr_LiffData = array_merge ( $arr_Default , $resultListLIFF [ 'apps' ][ $keyLIFF ]); } } echo json_encode( $arr_LiffData ); // ส่งข้อมูล liff app กลับในรูปแบบ json string ไปใช้งานต่อ exit ; } ?> |
อัพโหลดไฟล์ขึ้น Server จากนั้นให้เราแก้ไขผ่าน LIFF Manager ที่เราสร้างเดิม ที่ยังใช้ผ่าน liff.php โดยเปลี่ยน
เป็น liff_ajax.php กด Confirm

ทดสอบการทำงาน ดูได้ที่วิดีโอใน Demo 2
จากการใช้งาน LIFF Manager แบบ ajax จะพบว่ามีการทำงานที่รวดเร็วกว่าแบบ web app ปกติที่ใช้ PHP ยิ่งถ้ามีการ
ทำงานที่ซับซ้อน ยิ่งจะเห็นผลชัดเจน เพราะการใช้งานแบบ ajax หน้า web app จะเป็นในลักษณะ Single Page app
โหลดหรือแสดงข้อมูล เฉพาะส่วนที่ต้องการ
ต่อไปเป็นตัวอย่างสุดท้าย ตัวอย่างนี้เราจำเป้นต้องใช้ jQuery Plugin ซึ่งเป็นตัวที่ใช้ในการสร้างรูปวาดผ่าน canvas
ด้วย HTML 5 และ javascript โดยต้นฉบับ ของ plugin สามารถดูได้ที่
ไฟล์ jQuery Plugin: https://github.com/bobkovalex/Basic-Canvas-Paint
LIFF Drawing app
การทำงานคือ เราจะใช้ drawing app ที่ประยุกต์เพิ่มเติมแล้ว สร้างข้อมูลรูปภาพ โดยจะเป็นการไปดึง dataURI ที่
เป็นข้อมูลรูปภาพจาก canvas จากนั้น เราจะใช้ ajax ส่งข้อมูลไปยังไฟล์ php ที่ใช้ Intervention Image เป็น PHP library
สร้างไฟล์รูป 2 ไฟล์ เพื่อใช้ส่งไปยังห้องสนทนา โดย Line ต้องการ url ของไฟล์ต้นฉบับ original และ url ของไฟล์ preview
ข้อควรทราบอย่างหนึ่งสำหรับการส่งข้อมูลผ่าน LIFF SDK กรณีเป็น image audio และ video จะต่างจากการส่งแแบบปกติ
คือการส่งด้วย LIFF SDK จะเป็นการส่งแบบ external ส่วนการส่งโดยเลือกจากใน LINE app จะเป็นการส่งโดย line
ซึ่งการส่งโดย line จะสามารถรับด้วย message event ที่มี content ได้ แต่การส่งแบบ external จะใช้ url ของไฟล์
ต้นฉบับ และ url ของไฟล์ preview ขนาด 240x240 ไปใช้งานแทน แนวทางคร่าวๆ ประมาณนี้
โครงสร้างไฟล์ จะประกอบด้วย
>bot
> bot.php
> bot_action.php
>bot
>liff
>app1
|---> liff.php
|---> liff_ajax.php
|---> liffsdk.php
|---> liff_drawing.php
|---> save_draw.php
>bcPaint // โฟลเดอร์ drawing plugin
>images // กำหนด permission เป็น 755
>20190411 // สร้างอัตโนมัติในไฟล์ save_draw.php
|--->123456.png
|--->123456240x240.png
ไฟล์ liff_drawing.php เป็นไฟล์หลักหน้าวาดรูป
ไฟล์ save_draw.php เป็นไฟล์สำหรับบันทึกรูปลง server ในที่นี้เราจะบันทึกไว้ในโฟลเดอร์ images
และแยกย่อยด้วยโฟลเดอร์ ปีเดือนวัน (ตัวอย่าง เช่น 20190411) และสร้างไฟล์ original กับไฟล์
preview ขนาด 240x240 ด้วยค่า timestamp ตามโครงสร้างไฟล์ด้านบน
นั่นหมายความว่า ทุกครั้งที่เราส่งรูปยังห้องสนทนา จะมีการสร้างไฟล์รูปไว้บน server แล้ว ส่ง url ของ
รูปที่เราสร้างด้วย LIFF SDK เข้าไปในห้องสนทนา
ตัวอย่างรูปผลลัพธ์




เริ่มต้น ดาวน์โหลด drawing plugin ได้ที่ http://niik.in/download/bcPaint.rar
แล้วแตกไฟล์ เอาโฟลเดอร์ bcPaint ไว้ที่เดียวกับไฟล์ liff_drawing.php
ไฟล์ liff_drawing.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | <!doctype html> <html> <head> <meta charset= "utf-8" > <meta name= "viewport" content= "width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no" > <title>Drawing</title> <link type= "text/css" rel= "stylesheet" href= "bcPaint/css/bcPaint.css" /> <link type= "text/css" rel= "stylesheet" href= "bcPaint/css/bcPaint.mobile.css" /> </head> <body class = "bg-light" > <div class = "container bg-light" > <div id= "container" > <div id= "bcPaint" ></div> </div> <div id= "place_data" ></div> <div class = "form-group row mb-0 bg-light py-3 px-2 shadow-sm border-top fixed-bottom" > <div class = "col-6" > <button type= "button" name= "btnCancel" id= "btnCancel" value= "1" class = "btn btn-light bg-white btn-block shadow-sm" >Cancel</button> </div> <div class = "col-6" > <button type= "button" name= "btnSend" id= "btnSend" value= "1" class = "btn btn-primary btn-block shadow-sm" >Send</button> </div> </div> </div> <script type= "text/javascript" src= "bcPaint/js/bcPaint.js" ></script> <script type= "text/javascript" > $( function (){ // สร้าง canvas และเครื่องมือจัดการการวาดรูป $( '#bcPaint' ).bcPaint(); liff.init( function (data) { // คำสั่ง init() คืนค่าข้อมูลของ LIFF app }); // ทำคำสั่งสำปรับปิดหน้าต่าง LIFF app view $( "#btnCancel" ).on( "click" , function (){ liff.closeWindow(); }); // เมื่อวาดรูปแล้ว ต้องการส่งรูปไปในห้องสนทนา $( "#btnSend" ).on( "click" , function (){ // คำสั่ง $.fn.bcPaint.getImgData() เป็นการดึงข้อมูลรูปภาพจาก canvase // ถ้าไม่กำหนดสีด้เานใน จะเป็นพื้นหลังโปร่งใส ในที่นี้กำหนดสีพื้นหลังเป็นสีขาว var imgData = $.fn.bcPaint.getImgData( "#FFFFFF" ); // ส่งข้อมูลรูปไปยังไฟล์ สร้างรูปภาพ $.post( "save_draw.php" ,{ path: "images/" , // โฟลเดอร์หลักที่เก็บรูป imgData:imgData // ข้อมูลรูป }, function (data){ // ส่งกลับ json string กลับมาในตัวแปร data var resp = JSON.parse(data); // แปลง json string เป็น object var imagePath = "/bot/liff/app1/" ; // โฟลเดอร์ที่เก็บรูปที่สร้าง // ส่งรูป และ ข้อความ liff> ไปในห้องสนทนา liff.sendMessages([{ type: 'image' , },{ type: 'text' , text: "liff>" }]).then( function () { liff.closeWindow(); }). catch ( function (error) { window.alert( "Error sending message: " + error); liff.closeWindow(); }); }); }); }); </script> </body> </html> |
ไฟล์ save_draw.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | <?php // กรณีต้องการตรวจสอบการแจ้ง error ให้เปิด 3 บรรทัดล่างนี้ให้ทำงาน กรณีไม่ ให้ comment ปิดไป ini_set ( 'display_errors' , 1); ini_set ( 'display_startup_errors' , 1); error_reporting (E_ALL); // include composer autoload require_once '../../../vendor/autoload.php' ; // import the Intervention Image Manager Class use Intervention\Image\ImageManager; // สร้างตัวแปรอ้างอิง object ตัวจัดการรูปภาพ $manager = new ImageManager(); // รับข้อมูลรูปภาพที่ส่งมาผ่าน ajax if (isset( $_POST [ 'imgData' ]) && $_POST [ 'imgData' ]!= "" ){ $imgPath = $_POST [ 'path' ]; // รับ path โฟลเดอร์หลักที่เก็บรูป $imgFolder = date ( "Ymd" ); // กำหนดชื่อโฟลเดอร์ย่อยเก็บรูป $imgPath .= $imgFolder ; // path โฟลเดอร์เต็มที่เก็บรูป if (! file_exists ( $imgPath )) { // สร้างโฟลเอร์ย่อย ถ้ายังไม่มี @ mkdir ( $imgPath , 0777, true); } $imgFileName = time(). ".png" ; // กำหนดชื่อไฟล์รูป original $imgFileNamePreview = time(). "240x240.png" ; // กำหนดชื่อไฟล์รูป preview $newImgPath = $imgPath . "/" . $imgFileName ; // path เต็มไฟล์ original $previewImgPath = $imgPath . "/" . $imgFileNamePreview ; // path เต็มไฟล์ preview $contents = $_POST [ 'imgData' ]; // ข้อมูลรูปภาพ // สร้างและบันทึกรูป preview $manager ->make( $contents ) ->resize(240,240) ->save( $previewImgPath ); // สร้างและบันทึกรูปต้นฉบับ $manager ->make( $contents ) ->save( $newImgPath ); // สร้าง array ข้อมูล เพื่อส่งกลับไปใช้ในการส่งไปยังห้องสนทนาใน line $arr_img = array ( "original" => $newImgPath , "preview" => $previewImgPath ); echo json_encode( $arr_img ); // แปลงข้อมูลเป็น json stirng แล้วส่งกลับ exit ; } ?> |
สำหรับการใช้งาน Intervention Image สามารถดูการทำงาน และคำสั่งเพิ่มเติมได้ที่ http://niik.in/822
ไฟล์ save_draw.php จะรับข้อมูลรูปจาก ajax แล้วนำไปสร้างไฟล์รูปสองรูป เมื่อสร้างเสร็จ ก็จะส่ง path
ของไฟล์รูปทั้งสองกลับออกมาในรูปแบบ json string ตัวอย่าง
{
"original":"images/20190411/123456.png",
"preview":"images/20190411/123456240x240.png",
}
จากนั้นใช้คำสั่ง liff.sendMessages() เพื่อส่งรูปไปยังห้องสนทนา
การลบรูปที่ server มีผลต่อการแสดงรูปในห้องสนทนา เมื่อผู้ใช้กดดูรูปขนาดใหญ่ จะแสดงข้อความว่าไม่พบรูปนั้น
ดูวิดีโอขั้นตอนการสร้าง LIFF Drawing และการใช้งาน ได้ใน Demo 3
ทั้งหมดเป็นแนวทางการประยุกต์ ทั้งสามรูปแบบ สามารถใช้เป็นไอเดีย หรือ
นำไปดัดแปลงใช้งานได้ตามต้องการ