fix: kirim WA tidak menutup aplikasi — fetch AJAX + SweetAlert dengan tombol Buka WhatsApp (tab baru, aplikasi tetap terbuka) + test JSON

This commit is contained in:
Sari
2026-08-03 09:46:00 +07:00
parent 47c5cdb48f
commit 156841a4e7
3 changed files with 93 additions and 7 deletions
+32 -4
View File
@@ -5,6 +5,7 @@ namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
@@ -128,15 +129,18 @@ class UserController extends Controller
/**
* Kirim akun (link + username + password baru) ke nomor HP user via WhatsApp.
* Password lama tidak bisa dikirim (tersimpan hash) — jadi dibuatkan password baru.
*
* Jika request AJAX/JSON → kembalikan URL wa.me (aplikasi tetap terbuka,
* WhatsApp dibuka di tab baru). Jika tidak → redirect away (fallback).
*/
public function sendWa(User $user): RedirectResponse
public function sendWa(Request $request, User $user): RedirectResponse|JsonResponse
{
if ($user->id === auth()->id()) {
return back()->with('error', 'Tidak perlu mengirim akun ke diri sendiri.');
return $this->waResponse($request, null, 'Tidak perlu mengirim akun ke diri sendiri.');
}
if (blank($user->phone)) {
return back()->with('error', 'Nomor HP belum diisi untuk ' . $user->name . ' — isi dulu di form edit user.');
return $this->waResponse($request, null, 'Nomor HP belum diisi untuk ' . $user->name . ' — isi dulu di form edit user.');
}
// Generate password baru yang mudah dibaca (8 karakter, tanpa karakter ambigu)
@@ -162,6 +166,30 @@ class UserController extends Controller
'Mohon segera login dan ganti password Anda. Terima kasih.',
]);
return redirect()->away('https://wa.me/'.$user->phone.'?text='.rawurlencode($message));
$waUrl = 'https://wa.me/'.$user->phone.'?text='.rawurlencode($message);
return $this->waResponse($request, $waUrl, null, [
'name' => $user->name,
'username' => $user->username,
'password' => $password,
'app_name' => $appName,
'app_url' => $appUrl,
]);
}
protected function waResponse(Request $request, ?string $url, ?string $error, array $extra = []): RedirectResponse|JsonResponse
{
if ($request->expectsJson() || $request->ajax()) {
return response()->json(array_merge(
$extra,
['url' => $url, 'error' => $error]
), $error ? 422 : 200);
}
if ($error) {
return back()->with('error', $error);
}
return redirect()->away($url);
}
}
+39 -3
View File
@@ -367,9 +367,45 @@ function sendWaData(userId, userName, hasPhone) {
showCancelButton: true,
cancelButtonText: 'Batal',
}).then((result) => {
if (result.isConfirmed && form) {
form.submit();
}
if (!result.isConfirmed || !form) return;
fetch(form.action, {
method: 'POST',
headers: {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
'Accept': 'application/json',
},
})
.then(r => r.json().catch(() => ({ error: 'Respons tidak valid dari server' })))
.then(data => {
if (data.error) {
Swal.fire({ icon: 'error', title: 'Gagal', text: data.error });
return;
}
const msgLines = [
'<b>📲 Akun Aplikasi ' + (data.app_name || '') + '</b>',
'Yth. ' + (data.name || userName) + ',',
'Link: ' + (data.app_url || ''),
'Username: <b>' + (data.username || '') + '</b>',
'Password: <b>' + (data.password || '') + '</b>',
'<span style="color:#6b7280;font-size:12px">Mohon segera ganti password setelah login.</span>',
].join('<br>');
Swal.fire({
icon: 'success',
title: 'Akun Siap Dikirim',
html: '<div style="text-align:left;font-size:13px;line-height:1.8">' + msgLines + '</div>' +
'<a href="' + data.url + '" target="_blank" rel="noopener" ' +
'style="display:inline-block;margin-top:16px;padding:11px 26px;background:#25D366;color:#fff;' +
'border-radius:12px;font-weight:700;text-decoration:none;font-size:14px">' +
'<i class="fa-brands fa-whatsapp"></i> Buka WhatsApp</a>' +
'<p style="font-size:11px;color:#9ca3af;margin-top:10px">WhatsApp dibuka di tab baru — aplikasi tetap terbuka.</p>',
showConfirmButton: false,
showCloseButton: true,
});
})
.catch(() => {
Swal.fire({ icon: 'error', title: 'Gagal', text: 'Tidak dapat menghubungi server.' });
});
});
}
};
+22
View File
@@ -100,4 +100,26 @@ class UserManagementTest extends TestCase
$this->assertFalse(str_contains(session('error'), 'wa.me'));
}
public function test_kirim_akun_via_json_mengembalikan_url_dan_aplikasi_tetap_terbuka(): void
{
$user = User::factory()->create([
'roles' => ['bk'],
'phone' => '081234567890',
'username' => 'guruwa2',
'password' => 'passwordlama',
]);
$response = $this->actingAs($this->admin)
->post("/users/{$user->id}/send-wa", [], ['Accept' => 'application/json']);
$response->assertOk()
->assertJsonStructure(['url', 'password', 'username'])
->assertJsonPath('username', 'guruwa2');
$url = $response->json('url');
$this->assertStringStartsWith('https://wa.me/081234567890?text=', $url);
$this->assertStringContainsString('guruwa2', urldecode($url));
$this->assertStringContainsString($response->json('password'), urldecode($url));
}
}