Initial baseline WACloud CI3 production
This commit is contained in:
@@ -0,0 +1,481 @@
|
||||
<?php
|
||||
defined('BASEPATH') OR exit('No direct script access allowed');
|
||||
|
||||
class Chat extends CI_Controller {
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
if (!$this->session->userdata('is_logged_in') || $this->session->userdata('role') != 'user') {
|
||||
redirect('auth');
|
||||
}
|
||||
$this->load->model('Chat_model', 'chat');
|
||||
$this->load->helper('Meta_helper', 'metaapi');
|
||||
}
|
||||
|
||||
// Halaman utama chat
|
||||
public function index()
|
||||
{
|
||||
$data['title'] = 'Chat Center';
|
||||
$data['content_view'] = 'chat/pages/index';
|
||||
$this->load->view('chat/layout/layout', $data);
|
||||
}
|
||||
|
||||
public function getContact()
|
||||
{
|
||||
$session_id = $this->session->userdata('user_id');
|
||||
$nomor = preg_replace('/\D/', '', $this->input->post('number')); // hanya angka
|
||||
|
||||
// 🔹 Validasi format nomor
|
||||
if (strlen($nomor) < 9) {
|
||||
echo json_encode([
|
||||
'status' => 'error',
|
||||
'message' => 'Nomor WhatsApp tidak valid.',
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
// 🔹 Ambil data session user (access_token dan phone_number_id)
|
||||
$datasession = $this->chat->get_session_detail($session_id);
|
||||
if (empty($datasession) || empty($datasession['access_token']) || empty($datasession['phone_number_id'])) {
|
||||
echo json_encode([
|
||||
'status' => 'error',
|
||||
'message' => 'Session WhatsApp tidak ditemukan atau tidak valid.',
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$access_token = $datasession['access_token'];
|
||||
$phone_number_id = $datasession['phone_number_id'];
|
||||
|
||||
// 🔹 URL endpoint Meta API
|
||||
$url = "https://graph.facebook.com/v20.0/{$phone_number_id}/contacts?contacts={$nomor}";
|
||||
|
||||
$headers = [
|
||||
"Authorization: Bearer {$access_token}",
|
||||
"Content-Type: application/json"
|
||||
];
|
||||
|
||||
$context = stream_context_create([
|
||||
"http" => [
|
||||
"method" => "GET",
|
||||
"header" => implode("\r\n", $headers),
|
||||
"ignore_errors" => true
|
||||
]
|
||||
]);
|
||||
|
||||
$response = @file_get_contents($url, false, $context);
|
||||
|
||||
// 🔹 Cek apakah request berhasil
|
||||
if ($response === false) {
|
||||
echo json_encode([
|
||||
'status' => 'error',
|
||||
'message' => 'Tidak dapat menghubungi API Meta.',
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$data = json_decode($response, true);
|
||||
|
||||
|
||||
|
||||
// 🔹 Jika sukses (nomor valid)
|
||||
echo json_encode([
|
||||
'status' => 'success',
|
||||
'message' => 'keterangan',
|
||||
'data' => [
|
||||
'nomor' => $nomor,
|
||||
'input' => $data
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function getSessions()
|
||||
{
|
||||
$wa_id = (int) $this->input->get('whatsapp_id');
|
||||
$limit = (int) $this->input->get('limit') ?? 15;
|
||||
$offset = (int) $this->input->get('offset') ?? 0;
|
||||
$search = $this->input->get('search');
|
||||
$filter = $this->input->get('filter'); // 'all' atau 'unread'
|
||||
|
||||
// Ambil data dengan limit & filter
|
||||
$sessions = $this->chat->get_sessions_paginated($wa_id, $limit, $offset, $search, $filter);
|
||||
|
||||
// Ambil total (untuk pagination)
|
||||
$total = $this->chat->count_sessions($search, $filter);
|
||||
|
||||
echo json_encode([
|
||||
'status' => true,
|
||||
'data' => $sessions,
|
||||
'total' => (int) $total
|
||||
]);
|
||||
}
|
||||
|
||||
// 🔹 Ambil chat window
|
||||
public function getMessages($session_id)
|
||||
{
|
||||
if (!is_numeric($session_id)) {
|
||||
echo json_encode([
|
||||
'status' => false,
|
||||
'message' => 'Invalid session ID'
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$this->chat->updateStatusSession($session_id);
|
||||
$this->chat->updateUserMessage($session_id,$this->session->userdata('user_id'));
|
||||
$messages = $this->chat->get_messages_by_session($session_id);
|
||||
|
||||
echo json_encode([
|
||||
'status' => true,
|
||||
'data' => $messages
|
||||
]);
|
||||
}
|
||||
|
||||
// 🔹 Ambil chat window
|
||||
public function updateSession($session_id)
|
||||
{
|
||||
$update = $this->chat->updateStatusSession($session_id);
|
||||
echo json_encode([
|
||||
'status' => $update ? 'success' : 'failed',
|
||||
'message' => $update ? 'Session updated' : 'Update failed'
|
||||
]);
|
||||
}
|
||||
|
||||
public function getMessageStatus($message_id)
|
||||
{
|
||||
if (!is_numeric($message_id)) {
|
||||
echo json_encode([
|
||||
'status' => false,
|
||||
'message' => 'Invalid session ID'
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$messages = $this->chat->get_messages_by_id($message_id);
|
||||
|
||||
echo json_encode([
|
||||
'status' => true,
|
||||
'data' => $messages
|
||||
]);
|
||||
}
|
||||
|
||||
public function getMessagesTemplate()
|
||||
{
|
||||
$rawInput = file_get_contents("php://input");
|
||||
$content = json_decode($rawInput, true);
|
||||
|
||||
if (!$content || !isset($content['template']['name']) || !isset($content['to'])) {
|
||||
return $this->output
|
||||
->set_status_header(400)
|
||||
->set_content_type('application/json', 'utf-8')
|
||||
->set_output(json_encode(['success' => false, 'message' => 'Payload tidak valid']));
|
||||
}
|
||||
|
||||
$templateName = $content['template']['name'];
|
||||
$languageCode = $content['template']['language']['code'] ?? 'id';
|
||||
$phoneNumber = $content['to'];
|
||||
|
||||
$this->load->model('Chat_model');
|
||||
|
||||
$wa = $this->Chat_model->get_whatsapp_number_by_phone($phoneNumber);
|
||||
if (!$wa) {
|
||||
return $this->output
|
||||
->set_status_header(404)
|
||||
->set_content_type('application/json', 'utf-8')
|
||||
->set_output(json_encode(['success' => false, 'message' => 'Nomor WhatsApp tidak ditemukan']));
|
||||
}
|
||||
|
||||
$template = $this->Chat_model->get_template($wa->whatsapp_number_id, $templateName, $languageCode);
|
||||
if (!$template) {
|
||||
return $this->output
|
||||
->set_status_header(404)
|
||||
->set_content_type('application/json', 'utf-8')
|
||||
->set_output(json_encode(['success' => false, 'message' => 'Template tidak ditemukan']));
|
||||
}
|
||||
|
||||
// Pastikan komponen dalam UTF-8 (opsional)
|
||||
if (!mb_check_encoding($template->components, 'UTF-8')) {
|
||||
$template->components = mb_convert_encoding($template->components, 'UTF-8', 'auto');
|
||||
}
|
||||
$components = json_decode($template->components, true);
|
||||
|
||||
$bodyParams = [];
|
||||
$headerParams = [];
|
||||
$buttonsParams = [];
|
||||
if (!empty($content['template']['components'])) {
|
||||
foreach ($content['template']['components'] as $comp) {
|
||||
if (strtolower($comp['type']) === 'body' && isset($comp['parameters'])) {
|
||||
foreach ($comp['parameters'] as $param) {
|
||||
$bodyParams[] = $param['text'] ?? '';
|
||||
}
|
||||
}
|
||||
if (strtolower($comp['type']) === 'button' && isset($comp['parameters'])) {
|
||||
foreach ($comp['parameters'] as $param) {
|
||||
$buttonsParams[] = $param['text'] ?? '';
|
||||
}
|
||||
}
|
||||
if (strtolower($comp['type']) === 'header' && isset($comp['parameters'])) {
|
||||
foreach ($comp['parameters'] as $param) {
|
||||
$headerParams[] = $param;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// print_r($buttonsParams);
|
||||
$rendered = [
|
||||
'header' => '',
|
||||
'body' => '',
|
||||
'footer' => '',
|
||||
'buttons' => []
|
||||
];
|
||||
|
||||
foreach ($components as $comp) {
|
||||
switch (strtolower($comp['type'])) {
|
||||
case 'header':
|
||||
$format = strtoupper($comp['format'] ?? '');
|
||||
if ($format === 'TEXT') {
|
||||
$text = $comp['text'] ?? '';
|
||||
$rendered['header'] = preg_replace_callback('/\{\{(\d+)\}\}/', function ($matches) use ($headerParams) {
|
||||
$index = (int)$matches[1] - 1;
|
||||
return $headerParams[$index]['text'] ?? $matches[0];
|
||||
}, $text);
|
||||
} elseif (in_array($format, ['IMAGE', 'VIDEO', 'DOCUMENT'])) {
|
||||
// Ambil parameter media dari headerParams
|
||||
$mediaParam = $headerParams[0] ?? null;
|
||||
if ($mediaParam && isset($mediaParam[strtolower($format)]['link'])) {
|
||||
$rendered['header'] = [
|
||||
'type' => $format,
|
||||
'link' => $mediaParam[strtolower($format)]['link']
|
||||
];
|
||||
} else {
|
||||
$rendered['header'] = [
|
||||
'type' => $format,
|
||||
'link' => null
|
||||
];
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'body':
|
||||
$text = $comp['text'] ?? '';
|
||||
|
||||
// Tidak perlu detect encoding dan convert, asumsikan sudah UTF-8 dari DB
|
||||
|
||||
// Ganti placeholder {{n}} dengan bodyParams
|
||||
$renderedText = preg_replace_callback('/\{\{(\d+)\}\}/u', function ($matches) use ($bodyParams) {
|
||||
$index = (int)$matches[1] - 1;
|
||||
return $bodyParams[$index] ?? $matches[0];
|
||||
}, $text);
|
||||
|
||||
// Format markdown-style ke HTML
|
||||
$renderedText = preg_replace('/\*(.*?)\*/u', '<b>$1</b>', $renderedText);
|
||||
$renderedText = preg_replace('/_(.*?)_/u', '<i>$1</i>', $renderedText);
|
||||
$renderedText = preg_replace('/~(.*?)~/u', '<s>$1</s>', $renderedText);
|
||||
$renderedText = preg_replace('/\n/', '<br>', $renderedText);
|
||||
|
||||
$rendered['body'] = $renderedText;
|
||||
break;
|
||||
|
||||
case 'footer':
|
||||
$rendered['footer'] = $comp['text'] ?? '';
|
||||
break;
|
||||
|
||||
// case 'buttons':
|
||||
// if (!empty($comp['buttons'])) {
|
||||
// foreach ($comp['buttons'] as $btn) {
|
||||
|
||||
// $rendered['buttons'][] = [
|
||||
// 'type' => $btn['type'] ?? '',
|
||||
// 'text' => $btn['text'] ?? '',
|
||||
// 'url' => $btn['url'] ?? null,
|
||||
// 'phone_number' => $btn['phone_number'] ?? null
|
||||
// ];
|
||||
// }
|
||||
// }
|
||||
// break;
|
||||
|
||||
case 'buttons':
|
||||
if (!empty($comp['buttons'])) {
|
||||
foreach ($comp['buttons'] as $btn) {
|
||||
$type = strtolower($btn['type'] ?? '');
|
||||
$text = $btn['text'] ?? '';
|
||||
$buttonData = [
|
||||
'type' => strtoupper($type),
|
||||
'text' => $text,
|
||||
'url' => null,
|
||||
'phone_number' => null
|
||||
];
|
||||
|
||||
// 🔹 Handle tombol URL
|
||||
if ($type === 'url') {
|
||||
$urlTemplate = $btn['url'] ?? '';
|
||||
|
||||
if (preg_match('/\{\{(\d+)\}\}/', $urlTemplate)) {
|
||||
$renderedUrl = preg_replace_callback(
|
||||
'/\{\{(\d+)\}\}/',
|
||||
function ($matches) use ($buttonsParams) {
|
||||
$index = (int)$matches[1] - 1;
|
||||
|
||||
// jika tombol parameter berupa array dengan key 'text'
|
||||
if (isset($buttonsParams[$index]['text'])) {
|
||||
return $buttonsParams[$index]['text'];
|
||||
}
|
||||
|
||||
// jika tombol parameter berupa string langsung
|
||||
if (isset($buttonsParams[$index]) && is_string($buttonsParams[$index])) {
|
||||
return $buttonsParams[$index];
|
||||
}
|
||||
|
||||
// fallback: kembalikan {{1}} jika tidak ditemukan
|
||||
return $matches[0];
|
||||
},
|
||||
$urlTemplate
|
||||
);
|
||||
|
||||
$buttonData['url'] = $renderedUrl;
|
||||
} else {
|
||||
$buttonData['url'] = $urlTemplate;
|
||||
}
|
||||
}
|
||||
|
||||
// 🔹 Handle tombol Call-to-Action (PHONE_NUMBER)
|
||||
elseif ($type === 'phone_number') {
|
||||
$buttonData['phone_number'] = $btn['phone_number'] ?? null;
|
||||
}
|
||||
|
||||
// 🔹 Handle tombol Quick Reply
|
||||
elseif ($type === 'quick_reply') {
|
||||
// Tidak perlu URL / phone number
|
||||
}
|
||||
|
||||
// 🔹 Handle tombol Quick Reply
|
||||
elseif ($type === 'flow') {
|
||||
// Tidak perlu URL / phone number
|
||||
}
|
||||
|
||||
$rendered['buttons'][] = $buttonData;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->output
|
||||
->set_content_type('application/json; charset=utf-8')
|
||||
->set_output(json_encode([
|
||||
'success' => true,
|
||||
'data' => $rendered,
|
||||
'template_name' => $template->template_name
|
||||
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
|
||||
|
||||
}
|
||||
|
||||
public function sendMessageOut()
|
||||
{
|
||||
// Ambil raw JSON body
|
||||
$inputJSON = file_get_contents('php://input');
|
||||
$input = json_decode($inputJSON, true);
|
||||
|
||||
if (!$input || !is_array($input)) {
|
||||
$this->response_json(false, 'Data JSON tidak valid atau kosong');
|
||||
return;
|
||||
}
|
||||
|
||||
$session_id = $input['session_id'] ?? null;
|
||||
$message_text = $input['message'] ?? null;
|
||||
$user_id = $this->session->userdata('user_id');
|
||||
|
||||
if (!$session_id || !$message_text || !$user_id) {
|
||||
$this->response_json(false, 'Parameter wajib: session_id, message, user_id');
|
||||
return;
|
||||
}
|
||||
|
||||
$session = $this->chat->get_session_detail($session_id);
|
||||
|
||||
$customer_number = $session['customer_number'];
|
||||
$phone_number_id = $session['phone_number_id'];
|
||||
$access_token = $session['access_token'];
|
||||
|
||||
// 💾 Simpan ke tabel messages
|
||||
$this->db->insert('messages', [
|
||||
'session_id' => $session_id,
|
||||
'direction' => 'out',
|
||||
'message_type' => 'text',
|
||||
'message_body' => $message_text,
|
||||
'content' => json_encode(['body' => $message_text], JSON_UNESCAPED_UNICODE),
|
||||
'status' => 'pending', // belum dikirim
|
||||
'timestamp' => date('Y-m-d H:i:s'),
|
||||
'user_id' => $user_id
|
||||
]);
|
||||
|
||||
$message_id = $this->db->insert_id();
|
||||
|
||||
// 📤 Kirim ke Meta via helper
|
||||
$payload = [
|
||||
'messaging_product' => 'whatsapp',
|
||||
'to' => $customer_number,
|
||||
'type' => 'text',
|
||||
'text' => ['body' => $message_text]
|
||||
];
|
||||
|
||||
$endpoint = $phone_number_id . '/messages';
|
||||
$meta_response = meta_api_request($endpoint, 'POST', $payload, $access_token);
|
||||
|
||||
// 🔄 Update status sesuai respons Meta
|
||||
if (isset($meta_response['messages'][0]['id'])) {
|
||||
$status = 'sent';
|
||||
$whatsapp_message_id = $meta_response['messages'][0]['id'];
|
||||
} else {
|
||||
$status = 'failed';
|
||||
$whatsapp_message_id = null;
|
||||
}
|
||||
|
||||
$this->db->where('id', $message_id)->update('messages', [
|
||||
'status' => $status,
|
||||
'whatsapp_message_id' => $whatsapp_message_id
|
||||
]);
|
||||
|
||||
$this->db->select('
|
||||
m.id,
|
||||
m.session_id,
|
||||
m.direction,
|
||||
m.message_type,
|
||||
m.message_body,
|
||||
m.content,
|
||||
m.status,
|
||||
m.timestamp,
|
||||
f.file_name,
|
||||
f.file_url,
|
||||
f.mime_type,
|
||||
f.file_size,
|
||||
g.name
|
||||
');
|
||||
$this->db->from('messages m');
|
||||
$this->db->join('message_files f', 'f.message_id = m.id', 'left');
|
||||
$this->db->join('users g', 'g.id = m.user_id', 'left');
|
||||
$this->db->where('m.id', $message_id);
|
||||
$dataPesan = $this->db->get()->row_array();
|
||||
|
||||
|
||||
$this->response_json(true, 'Pesan diproses', $dataPesan);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Response JSON standar
|
||||
*/
|
||||
private function response_json($success, $message, $data = [])
|
||||
{
|
||||
header('Content-Type: application/json');
|
||||
echo json_encode([
|
||||
'success' => $success,
|
||||
'message' => $message,
|
||||
'data' => $data
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user