Initial baseline WACloud CI3 production

This commit is contained in:
WACloud Developer
2026-10-09 09:01:52 +00:00
commit a26ee48869
2054 changed files with 145580 additions and 0 deletions
+151
View File
@@ -0,0 +1,151 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Auth extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Auth_model');
}
public function index()
{
$this->load->helper('cookie');
// ✅ Jika sudah login (session aktif), langsung redirect saja
if ($this->session->userdata('is_logged_in')) {
if ($this->session->userdata('role') == 'admin') {
redirect('dashboard');
} else {
redirect('chat');
}
}
// ✅ Jika belum login tapi ada cookie remember_token
$token = get_cookie('remember_token');
if ($token) {
$user = $this->db->get_where('users', ['remember_token' => $token])->row_array();
if ($user) {
// Buat session baru dari data user
$this->session->set_userdata(array(
'user_id' => $user['id'],
'name' => $user['name'],
'username' => $user['username'],
'role' => $user['role'],
'whatsapp_id' => $user['whatsapp_id'],
'is_logged_in' => TRUE
));
// Redirect sesuai role
if ($user['role'] == 'admin') {
redirect('dashboard');
} else {
redirect('chat');
}
}
}
// Kalau tidak ada session dan cookie, tampilkan form login
$this->load->view('login/layout');
}
public function login_process()
{
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login/layout');
} else {
$username = trim($this->input->post('username'));
$password = $this->input->post('password');
// cek user berdasarkan username
$user = $this->Auth_model->get_user($username);
// =========================
// USERNAME TIDAK DITEMUKAN
// =========================
if (!$user) {
$this->session->set_flashdata(
'error',
'Username tidak ditemukan!'
);
redirect('auth');
}
// =========================
// PASSWORD SALAH
// =========================
if (!password_verify($password, $user['password'])) {
$this->session->set_flashdata(
'error',
'Password yang anda masukkan salah!'
);
redirect('auth');
}
// =========================
// LOGIN BERHASIL
// =========================
$session_data = array(
'user_id' => $user['id'],
'name' => $user['name'],
'username' => $user['username'],
'role' => $user['role'],
'whatsapp_id' => $user['whatsapp_id'],
'is_logged_in' => TRUE
);
$this->session->set_userdata($session_data);
// Buat token unik untuk auto login
$token = bin2hex(random_bytes(32));
// Simpan token ke database
$this->db
->where('id', $user['id'])
->update('users', [
'remember_token' => $token
]);
// Simpan cookie 30 hari
$cookie = array(
'name' => 'remember_token',
'value' => $token,
'expire' => 60 * 60 * 24 * 30,
'secure' => false, // ubah true jika HTTPS
'httponly' => true
);
$this->input->set_cookie($cookie);
// Redirect sesuai role
if ($user['role'] == 'admin') {
redirect('dashboard');
} else {
redirect('chat');
}
}
}
public function logout() {
delete_cookie('remember_token');
$this->session->sess_destroy();
redirect('auth');
}
}
+481
View File
@@ -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;
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Chat2 extends CI_Controller {
public function index()
{
$data['title'] = 'WhatsApp UI';
$this->load->view('chat2/layout', $data);
}
}
+68
View File
@@ -0,0 +1,68 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Dashboard extends CI_Controller
{
public function __construct()
{
parent::__construct();
// Cek sesi login dan role
if (
!$this->session->userdata('is_logged_in') ||
$this->session->userdata('role') !== 'admin'
) {
redirect('auth');
}
// ⚠️ Ganti nama alias agar tidak bentrok dengan nama class
$this->load->model('Dashboard_model', 'Dashboard');
}
public function index()
{
$data['phone_numbers'] = $this->Dashboard->get_phone_number($this->session->userdata('user_id'));
$this->load->view('templates/header');
$this->load->view('dashboard/layout', $data);
$this->load->view('templates/footer');
}
public function get_grafik()
{
$phone_number = $this->input->post('phone_number');
$date_start = $this->input->post('date_start');
$date_end = $this->input->post('date_end');
if (empty($phone_number) || empty($date_start) || empty($date_end)) {
echo json_encode(['error' => 'Parameter tidak lengkap']);
return;
}
// Ambil data WABA dan access token dari model
$data = $this->Dashboard->get_whatsapp_data_by_phone($phone_number);
if (!$data) {
echo json_encode(['error' => 'Nomor WhatsApp tidak ditemukan']);
return;
}
// Konversi tanggal ke epoch
$start_time = strtotime($date_start);
$end_time = strtotime($date_end);
// Ambil data analytics dari model
$analytics = $this->Dashboard->getAnalyticsByNumber(
$data->phone_waba_id,
$data->access_token,
$phone_number,
$start_time,
$end_time
);
// Kirim hasil ke frontend
$this->output
->set_content_type('application/json')
->set_output(json_encode($analytics));
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Device extends CI_Controller
{
public function __construct()
{
parent::__construct();
// Hanya admin yang bisa akses
if (!$this->session->userdata('is_logged_in') || $this->session->userdata('role') != 'admin') {
redirect('auth');
}
}
public function index()
{
$this->load->view('templates/header');
// Buat view untuk add device jika diperlukan
echo '<div class="container mt-4"><h1>Halaman Tambah Device</h1><p>Halaman ini hanya bisa diakses oleh admin.</p></div>';
$this->load->view('templates/footer');
}
}
+121
View File
@@ -0,0 +1,121 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Get_file extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('cronjob/Model_cron_file');
$this->load->database();
}
public function download($id = null)
{
$access_token = "EAAN0PjgeNRsBPqGqvuv48h90PQ6ZCo1StyQ5vSFBZB7UiyjFLxneRvz4xE0a66HbZBmY0rLo7cpsQV0Ecey3Ggy9UK36MJiSxQXebMexHLyKlFSTAbf6AUHO7EVQEaJvINxA51j4TMiq3InlIy7Yn9muxITYGvjB403uXcuD71MieL7Q1KEm8PXopiRqgZDZD"; // 🔑 WA Business API Access Token
if (empty($access_token)) {
$this->response_json(false, "ACCESS TOKEN tidak ditemukan");
return;
}
if (empty($id)) {
$this->response_json(false, "Parameter ID wajib diisi");
return;
}
// Ambil file yang masih pending
$file = $this->db->get_where('message_files', [
'id' => $id
])->row_array();
if (!$file) {
$this->response_json(false, "Tidak ada file pending dengan ID {$id}");
return;
}
$file_id = $file['id'];
$customer_number = $file['customer_number'];
$meta_url = $file['meta_url'];
$mime_type = $file['mime_type'] ?? 'application/octet-stream';
$ext = $this->get_extension_by_mime($mime_type);
$filename = "file_{$file_id}." . $ext;
$max_attempts = 3;
$success = false;
for ($attempt = 1; $attempt <= $max_attempts; $attempt++) {
echo "▶️ Percobaan {$attempt}/{$max_attempts} untuk file ID {$file_id}\n";
$content = $this->Model_cron_file->download_file_from_meta($meta_url, $access_token);
if ($content !== false && strlen($content) > 0) {
// ✅ Update status menjadi downloading
$this->Model_cron_file->update_file_status($file_id, 'downloading');
// Simpan file ke folder lokal
$file_url = $this->Model_cron_file->save_file_to_local($customer_number, $filename, $content);
$file_path = FCPATH . ltrim($file_url, '/');
$file_size = file_exists($file_path) ? filesize($file_path) : 0;
if ($file_size > 100) {
// ✅ Update status sukses
$this->Model_cron_file->update_file_status($file_id, 'downloaded', $file_url, $filename, $file_size);
$this->response_json(true, "Berhasil download {$filename} ({$file_size} bytes)", [
'file_id' => $file_id,
'url' => $file_url,
'size' => $file_size
]);
$success = true;
break; // selesai, keluar dari loop
}
}
// ⚠️ Jika belum berhasil, beri info dan tunggu sebelum retry
if (!$success && $attempt < $max_attempts) {
echo "⚠️ File belum siap diunduh (percobaan {$attempt}). Menunggu 2 detik sebelum retry...\n";
sleep(2);
}
}
if (!$success) {
// ❌ Setelah 3x gagal, biarkan status tetap pending
log_message('error', "File ID {$file_id} gagal diunduh setelah {$max_attempts} percobaan. Tetap pending.");
$this->response_json(false, "File belum siap diunduh, masih pending setelah {$max_attempts} percobaan");
}
}
private function get_extension_by_mime($mime)
{
$map = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'video/mp4' => 'mp4',
'audio/mpeg' => 'mp3',
'audio/ogg' => 'ogg',
'application/pdf' => 'pdf',
'application/msword' => 'doc',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
'text/plain' => 'txt',
];
return $map[$mime] ?? 'bin';
}
/**
* Fungsi respon JSON standar agar bisa dibaca dari Node.js
*/
private function response_json($success, $message, $data = [])
{
$response = [
'success' => $success,
'message' => $message,
'data' => $data
];
header('Content-Type: application/json');
echo json_encode($response);
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Testdb extends CI_Controller {
public function index() {
$query = $this->db->query("SHOW TABLES");
foreach ($query->result_array() as $row) {
echo reset($row) . "<br>"; // ambil nilai pertama tanpa peduli nama kolom
}
}
}
+133
View File
@@ -0,0 +1,133 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class User_management extends CI_Controller
{
public function __construct()
{
parent::__construct();
// Hanya admin yang bisa akses
if (!$this->session->userdata('is_logged_in') || $this->session->userdata('role') != 'admin') {
redirect('auth');
}
// Load model manajemen user
$this->load->model('User_management_model');
}
public function index()
{
$this->load->view('templates/header');
$this->load->view('user/itemlist');
$this->load->view('templates/footer');
}
// Fungsi untuk menampilkan halaman tambah user
public function get_list() {
$session_id = $this->session->userdata('user_id');
if ($session_id == 1) {
$data = $this->User_management_model->get_all_users();
} else {
$data = $this->User_management_model->get_users_by_session_id($session_id);
}
echo json_encode($data);
}
// Fungsi untuk menampilkan halaman tambah user
public function add() {
$session_id = $this->session->userdata('user_id');
$data['phone_numbers'] = $this->User_management_model->get_phone_number_id($session_id);
$this->load->view('user/add', $data);
}
// Fungsi untuk menampilkan halaman edit user
public function edit($id) {
$session_id = $this->session->userdata('user_id');
$data['user'] = $this->User_management_model->get_user_by_id($id);
$data['phone_numbers'] = $this->User_management_model->get_phone_number_id($session_id);
$this->load->view('user/edit', $data);
}
public function delete($id)
{
$result = $this->User_management_model->delete($id);
if ($result) {
echo json_encode([
'status' => 'success',
'message' => 'User berhasil dihapus.'
]);
} else {
echo json_encode([
'status' => 'error',
'message' => 'User tidak ditemukan atau gagal dihapus.'
]);
}
}
// 🔹 Fungsi Simpan (Add/Edit)
public function save() {
$id = $this->input->post('id');
$name = $this->input->post('name');
$username = $this->input->post('username');
$password = $this->input->post('password');
$role = $this->input->post('role') ?? 'user';
$whatsapp_id = $this->input->post('whatsapp_id') ?? NULL;
$master_id = ($this->session->userdata('user_id') == 6) ? 0 : $this->session->userdata('user_id');
$wa_id = ($role == 'user') ? : NULL ;
// Ubah awalan huruf Besar
$name = ucwords(strtolower(trim($name)));
// Ubah username jadi lowercase dan hanya huruf + angka
$username = strtolower(trim($username));
$username = preg_replace('/[^a-z0-9]/', '', $username);
if (empty($name) || empty($username) || empty($role)) {
echo json_encode(['status' => 'error', 'message' => 'Semua field wajib diisi!']);
return;
}
if ($id) {
// Mode Edit (password tidak ikut diubah)
$data = [
'name' => $name,
'username' => $username,
'whatsapp_id' => $whatsapp_id,
'role' => $role
];
$update = $this->User_management_model->update($id, $data);
if ($update) {
echo json_encode(['status' => 'success', 'message' => 'Data berhasil diperbarui']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Tidak ada perubahan data']);
}
} else {
// Mode Tambah Baru
if (empty($password)) {
echo json_encode(['status' => 'error', 'message' => 'Password wajib diisi untuk user baru!']);
return;
}
$data = [
'master_id' => $master_id,
'name' => $name,
'username' => $username,
'password' => password_hash($password, PASSWORD_BCRYPT),
'whatsapp_id' => $whatsapp_id,
'role' => $role
];
$insert = $this->User_management_model->insert($data);
if ($insert) {
echo json_encode(['status' => 'success', 'message' => 'Data berhasil disimpan']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Gagal menyimpan data']);
}
}
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see https://codeigniter.com/userguide3/general/urls.html
*/
public function index()
{
$this->load->view('welcome_message');
}
}
@@ -0,0 +1,100 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Cron_file extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('cronjob/Model_cron_file');
$this->load->database();
// Jalankan hanya dari CLI atau cron job (opsional)
if (!$this->input->is_cli_request()) {
// Boleh nonaktifkan kalau kamu mau bisa testing via browser
// show_error('This script can only be run from CLI or cron.', 403);
}
}
/**
* Endpoint cron / worker untuk download file WhatsApp (gambar/audio/video)
*/
public function index()
{
// Ganti dengan access token WA Business API kamu
$access_token = "EAAN0PjgeNRsBPqGqvuv48h90PQ6ZCo1StyQ5vSFBZB7UiyjFLxneRvz4xE0a66HbZBmY0rLo7cpsQV0Ecey3Ggy9UK36MJiSxQXebMexHLyKlFSTAbf6AUHO7EVQEaJvINxA51j4TMiq3InlIy7Yn9muxITYGvjB403uXcuD71MieL7Q1KEm8PXopiRqgZDZD"; // <--- PENTING: isi dengan token aktif
if (empty($access_token)) {
echo "❌ ACCESS TOKEN tidak ditemukan. Mohon isi di controller.\n";
return;
}
$files = $this->Model_cron_file->get_pending_files(10);
if (empty($files)) {
echo "ℹ️ Tidak ada file pending untuk diunduh.\n";
return;
}
foreach ($files as $file) {
$file_id = $file['id'];
$customer_number = $file['customer_number'];
$meta_url = $file['meta_url'];
$mime_type = $file['mime_type'] ?? 'application/octet-stream';
$ext = $this->get_extension_by_mime($mime_type);
$filename = "file_{$file_id}." . $ext;
echo "\n▶️ Proses file ID {$file_id} ({$mime_type})...\n";
// Update status awal
$this->Model_cron_file->update_file_status($file_id, 'downloading');
// Ambil konten binary dari Meta Graph API
$content = $this->Model_cron_file->download_file_from_meta($meta_url, $access_token);
if ($content !== false && strlen($content) > 0) {
// Simpan ke folder lokal
$file_url = $this->Model_cron_file->save_file_to_local($customer_number, $filename, $content);
// Cek ukuran file
$file_path = FCPATH . ltrim($file_url, '/');
$file_size = file_exists($file_path) ? filesize($file_path) : 0;
// Update status sukses
$this->Model_cron_file->update_file_status($file_id, 'downloaded', $file_url, $filename, $file_size);
echo "✅ Berhasil download {$filename} ({$file_size} bytes)\n";
} else {
// Update status error
$this->Model_cron_file->update_file_status($file_id, 'error');
echo "❌ Gagal download file {$filename}\n";
// Tambahkan log detail
log_message('error', "Gagal ambil file ID {$file_id} dari Meta URL: {$meta_url}");
}
}
echo "\nSelesai memproses file pending.\n";
}
/**
* Tentukan ekstensi file berdasarkan MIME type
*/
private function get_extension_by_mime($mime)
{
$map = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'video/mp4' => 'mp4',
'audio/mpeg' => 'mp3',
'audio/ogg' => 'ogg',
'application/pdf' => 'pdf',
'application/msword' => 'doc',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
'text/plain' => 'txt',
];
return $map[$mime] ?? 'bin';
}
}
@@ -0,0 +1,64 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Whatsapp_template extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('cronjob/WhatsappTemplate_model');
}
public function index($phone_number = null)
{
if (!$phone_number) {
$this->output
->set_status_header(400)
->set_content_type('application/json')
->set_output(json_encode(['success' => false, 'message' => 'Parameter phone_number dibutuhkan di URL']));
return;
}
$wa_number = $this->WhatsappTemplate_model->get_whatsapp_number_by_phone($phone_number);
if (!$wa_number) {
$this->output
->set_status_header(404)
->set_content_type('application/json')
->set_output(json_encode(['success' => false, 'message' => 'Nomor WhatsApp tidak ditemukan']));
return;
}
$templates = $this->WhatsappTemplate_model->get_templates_from_meta($wa_number->phone_waba_id,$wa_number->access_token);
if (!isset($templates['data'])) {
$this->output
->set_status_header(500)
->set_content_type('application/json')
->set_output(json_encode(['success' => false, 'message' => 'Gagal mengambil data template dari Meta']));
return;
}
$saved = [];
foreach ($templates['data'] as $template) {
$data = [
'template_id' => $template['id'],
'template_name' => $template['name'],
'language' => $template['language'],
'category' => $template['category'],
'status' => $template['status'],
'components' => json_encode($template['components']),
'last_updated' => date('Y-m-d H:i:s'),
'whatsapp_number_id' => $wa_number->id,
];
$this->WhatsappTemplate_model->upsert_template($data);
// $saved[] = $data;
}
$this->output
->set_content_type('application/json')
->set_output(json_encode(['success' => true, 'message' => 'Sinkronisasi selesai']));
}
}
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+360
View File
@@ -0,0 +1,360 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Receive extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function index()
{
header('Content-Type: application/json');
// ✅ 1. Verifikasi Webhook dari Meta
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$verify_token = '9b8f999598fb2d51504c1062f15b2e26b9db19786b0bc67e5a54695ac37653d1'; // ubah dengan token kamu
$mode = $this->input->get('hub_mode');
$token = $this->input->get('hub_verify_token');
$challenge = $this->input->get('hub_challenge');
if ($mode === 'subscribe' && $token === $verify_token) {
echo $challenge;
exit;
} else {
http_response_code(403);
exit;
}
}
// ✅ 2. Terima data JSON dari Meta
$input = file_get_contents('php://input');
$data = json_decode($input, true);
// Simpan log mentah
$this->db->insert('logs', [
'event' => 'webhook_received',
'data' => json_encode($data)
]);
if (!isset($data['entry'][0]['changes'][0])) {
http_response_code(400);
echo json_encode(['status' => 'no_change']);
exit;
}
$change = $data['entry'][0]['changes'][0];
$value = $change['value'] ?? [];
$name = $value['contacts'][0]['profile']['name'] ?? '';
$messages = $value['messages'] ?? [];
$statuses = $value['statuses'] ?? [];
$metadata = $value['metadata'] ?? [];
$phone_number_id = $metadata['phone_number_id'] ?? null;
if (!$phone_number_id) {
http_response_code(400);
echo json_encode(['status' => 'no_phone_id']);
exit;
}
// Ambil data akun WA dari DB
$whatsapp_number = $this->db->where('phone_number_id', $phone_number_id)
->get('whatsapp_numbers')
->row_array();
if (!$whatsapp_number) {
http_response_code(404);
echo json_encode(['status' => 'unknown_number']);
exit;
}
//
// 📥 PESAN MASUK
//
if (!empty($messages)) {
foreach ($messages as $msg) {
$from = $msg['from'];
$msg_id = $msg['id'] ?? null;
$type = $msg['type'] ?? 'unknown';
$timestamp = isset($msg['timestamp'])
? date('Y-m-d H:i:s', $msg['timestamp'])
: date('Y-m-d H:i:s');
$text = '';
$content = null;
switch ($type) {
case 'text':
$text = $msg['text']['body'] ?? '';
$content = $msg['text'] ?? null;
break;
case 'image':
$text = '[Gambar diterima]';
$content = [
'id' => $msg['image']['id'] ?? '',
'mime_type' => $msg['image']['mime_type'] ?? '',
'caption' => $msg['image']['caption'] ?? ''
];
break;
case 'document':
$text = '[Dokumen diterima]';
$content = [
'id' => $msg['document']['id'] ?? '',
'filename' => $msg['document']['filename'] ?? '',
'mime_type' => $msg['document']['mime_type'] ?? '',
'caption' => $msg['document']['caption'] ?? ''
];
break;
case 'audio':
$text = '[Audio diterima]';
$content = [
'id' => $msg['audio']['id'] ?? '',
'mime_type' => $msg['audio']['mime_type'] ?? '',
'voice' => $msg['audio']['voice'] ?? false
];
break;
case 'video':
$text = '[Video diterima]';
$content = [
'id' => $msg['video']['id'] ?? '',
'mime_type' => $msg['video']['mime_type'] ?? '',
'caption' => $msg['video']['caption'] ?? ''
];
break;
case 'sticker':
$text = '[Stiker diterima]';
$content = [
'id' => $msg['sticker']['id'] ?? '',
'mime_type' => $msg['sticker']['mime_type'] ?? ''
];
break;
case 'location':
$text = '[Lokasi diterima]';
$content = [
'latitude' => $msg['location']['latitude'] ?? '',
'longitude' => $msg['location']['longitude'] ?? '',
'name' => $msg['location']['name'] ?? '',
'address' => $msg['location']['address'] ?? ''
];
break;
case 'contacts':
$text = '[Kontak diterima]';
$content = $msg['contacts'] ?? [];
break;
case 'button':
$text = '[Tombol ditekan]';
$content = [
'button' => $msg['button']['text'] ?? '',
'payload' => $msg['button']['payload'] ?? ''
];
break;
case 'interactive':
$text = '[Interaksi diterima]';
$interactive = $msg['interactive'] ?? [];
$content = $interactive;
if (isset($interactive['button_reply'])) {
$text = '[Tombol Dipilih] ' . ($interactive['button_reply']['title'] ?? '');
} elseif (isset($interactive['list_reply'])) {
$text = '[List Dipilih] ' . ($interactive['list_reply']['title'] ?? '');
}
break;
default:
$text = '[Pesan tipe ' . $type . ']';
$content = $msg ?? null;
}
// 🔍 Cari atau buat session
$session = $this->db->where([
'customer_number' => $from,
'whatsapp_number_id' => $whatsapp_number['id']
])->order_by('id', 'DESC')->get('sessions')->row_array();
if (!$session) {
$this->db->insert('sessions', [
'whatsapp_number_id' => $whatsapp_number['id'],
'user_id' => 1,
'customer_number' => $from,
'customer_name' => $name,
'status' => 'open'
]);
$session_id = $this->db->insert_id();
} else {
$session_id = $session['id'];
if (!empty($name) && $session['customer_name'] !== $name) {
$this->db->where('id', $session_id)->update('sessions', [
'customer_name' => $name
]);
}
}
// 💾 Simpan pesan ke tabel messages
$this->db->insert('messages', [
'session_id' => $session_id,
'direction' => 'in',
'message_type' => $type,
'message_body' => $text,
'content' => json_encode($content, JSON_UNESCAPED_UNICODE),
'whatsapp_message_id' => $msg_id,
'status' => 'received',
'timestamp' => $timestamp
]);
$message_db_id = $this->db->insert_id();
$hasFile = false;
$insertId = null;
// ✅ Simpan ke message_files kalau ada file/media
if (in_array($type, ['image','document','audio','video','sticker'])) {
$media_id = $content['id'] ?? null;
$mime_type = $content['mime_type'] ?? null;
$meta_url = "https://graph.facebook.com/v20.0/{$media_id}";
$this->db->insert('message_files', [
'message_id' => $message_db_id,
'customer_number' => $from,
'meta_id' => $media_id,
'meta_url' => $meta_url,
'mime_type' => $mime_type,
'status' => 'pending',
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
]);
$insertId = $this->db->insert_id();
$hasFile = true;
}
// ⏰ Update waktu terakhir session
$this->db->where('id', $session_id)->update('sessions', [
'last_message_at' => date('Y-m-d H:i:s'),
'status' => 'open'
]);
$successDownload = true;
// Jika ada file, download dulu
if ($hasFile && $insertId) {
$url = base_url('get_file/download/' . $insertId);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // timeout 10 detik
$downloadResponse = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$decoded = json_decode($downloadResponse, true);
// Cek sukses download: JSON valid dan status success=true
if (!$decoded || !isset($decoded['success']) || $decoded['success'] !== true) {
$successDownload = false;
log_message('error', "File ID {$insertId} gagal diunduh. Response: " . $downloadResponse);
}
}
// Kirim ke Node.js hanya jika:
// 1. Tidak ada file, atau
// 2. Ada file tapi berhasil di-download
$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_db_id);
$dataPesan = $this->db->get()->row_array();
$payload = [
'sender_id' => 1,
'receiver_id' => $whatsapp_number['id'],
'session_id' => $session_id,
'message' => $dataPesan,
'direction' => 'in'
];
$nodeJsUrl = 'http://manjapro.net:2233/triggerMessage';
$ch = curl_init($nodeJsUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
$nodeResponse = curl_exec($ch);
$nodeHttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($nodeHttpCode !== 200) {
log_message('error', "Gagal kirim pesan ID {$message_db_id} ke Node.js. HTTP: {$nodeHttpCode}, Response: {$nodeResponse}");
}
}
}
//
// 📤 STATUS PESAN KELUAR
//
if (!empty($statuses)) {
foreach ($statuses as $status) {
$message_id = $status['id'];
$recipient_id = $status['recipient_id'] ?? '';
$status_name = $status['status'];
$timestamp = date('Y-m-d H:i:s', $status['timestamp']);
// Update status di messages
$this->db
->where('whatsapp_message_id', $message_id)
->update('messages', [
'status' => $status_name
]);
// Log status
$this->db->insert('logs', [
'event' => 'message_status',
'data' => json_encode([
'message_id' => $message_id,
'recipient_id' => $recipient_id,
'status' => $status_name,
'timestamp' => $timestamp
])
]);
// // Update status di messages
// $this->db
// ->where('id', $session_id)
// ->update('sessions', [
// 'last_message_at' => date('Y-m-d H:i:s'),
// 'status' => 'open'
// ]);
}
}
echo json_encode(['status' => 'ok']);
exit;
}
}
+82
View File
@@ -0,0 +1,82 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Send extends CI_Controller {
public function index()
{
$raw = file_get_contents('php://input');
$input = json_decode($raw, true);
if (!$input || !isset($input['data'])) {
log_message('error', 'Invalid payload from app1: ' . $raw);
show_error('Invalid payload', 400);
return;
}
$data = $input['data'];
$phone_number_id = $input['phone_id'];
$respon = isset($input['respon']) ? json_decode($input['respon'], true) : null;
// ambil nomor tujuan dari payload
$toNumber = $data['to'] ?? null;
$messageType = $data['type'] ?? 'text';
$messageBody = '';
if ($messageType === 'text' && isset($data['text']['body'])) {
$messageBody = $data['text']['body'];
} elseif ($messageType === 'template') {
$messageBody = '[Template] ' . ($data['template']['name'] ?? '');
}
// ambil whatsapp_message_id dari respon Meta API
$waMessageId = $respon['messages'][0]['id'] ?? null;
$status = isset($respon['messages'][0]) ? 'sent' : 'failed';
// Ambil data akun WA dari DB
$whatsapp_number = $this->db->where('phone_number_id', $phone_number_id)
->get('whatsapp_numbers')
->row_array();
// cari session_id berdasarkan nomor tujuan
$session = $this->db->where([
'customer_number' => $toNumber,
'whatsapp_number_id' => $whatsapp_number['id']
])->order_by('id', 'DESC')->get('sessions')->row_array();
if (!$session) {
$this->db->insert('sessions', [
'whatsapp_number_id' => $whatsapp_number['id'],
'user_id' => 1,
'customer_number' => $toNumber,
'customer_name' => null,
'status' => 'closed'
]);
$session_id = $this->db->insert_id();
} else {
$session_id = $session['id'];
}
// simpan ke tabel messages
$this->db->insert('messages', [
'session_id' => $session_id,
'direction' => 'out',
'message_type' => $messageType,
'message_body' => $messageBody,
'content' => json_encode($data, JSON_UNESCAPED_UNICODE),
'whatsapp_message_id' => $waMessageId,
'status' => $status,
'timestamp' => date('Y-m-d H:i:s')
]);
// kirim respon ke app1
$this->output
->set_status_header(200)
->set_content_type('application/json')
->set_output(json_encode([
'status' => 'ok',
'session_id' => $session_id,
'wa_message_id' => $waMessageId
]));
}
}