File size: 3,737 Bytes
89a1081
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<?php

namespace App\Http\Controllers;

use App\Enums\CommunicationStatusEnum;
use App\Enums\ServiceType;
use Exception;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\CommunicationLog;
use App\Models\PostWebhookLog;
use App\Service\Admin\Dispatch\WhatsAppService;
use Carbon\Carbon;

class WebhookController extends Controller
{
    public function postWebhook(Request $request, WhatsAppService $whatsAppService) {
        
        try {

            if ($request->isMethod('get')) {

                $apiKey = site_settings("webhook_verify_token");
                $query  = $request->query();
                $hubMode   = $query["hub_mode"] ?? null;
                $hubToken  = $query["hub_verify_token"] ?? null;
                $challenge = $query["hub_challenge"] ?? null;
                $usersCount = User::where("webhook_token", $hubToken)->count();
                
                if ($hubMode && $hubToken && $hubMode === 'subscribe' && ($hubToken === $apiKey || $usersCount > 0)) {

                    return response($challenge, 200)->header('Content-Type', 'text/plain');
                } else {

                    throw new Exception("Invalid Request");
                }
            } else {

                $request      = request()->all();
                $user         = User::where('uid',request()->input('uid'))->first();
                
                $webhookLog   = PostWebhookLog::create([
                    'user_id'           => $user ? $user->id : null,
                    'webhook_response'  => json_encode($request)
                ]);
                
                $response      = json_decode($webhookLog->webhook_response, true);
                $idFromRequest = $response["entry"][0]['changes'][0]['value']['statuses'][0]['id'] ?? null;
        
                if ($idFromRequest) {

                    $whatsappLog = CommunicationLog::where("type", ServiceType::WHATSAPP->value)->whereJsonContains('response_message->messages', [['id' => $idFromRequest]])->first();
                    if ($whatsappLog) {

                        $errors = $response['entry'][0]['changes'][0]['value']['statuses'][0]['errors'] ?? [];
                        if (!empty($errors)) {

                            $whatsappLog->status = (string) CommunicationStatusEnum::FAIL->value;
                            $whatsAppService->addedCreditLog($whatsappLog, $errors[0]['message']);
                            $whatsappLog->save();
                        } else {
                            
                            $status = $response['entry'][0]['changes'][0]['value']['statuses'][0]['status'];
                            if ($status == 'failed') {

                                $whatsappLog->status = (string) CommunicationStatusEnum::FAIL->value;
                                $whatsAppService->addedCreditLog($whatsappLog, "Cloud API couldnt send the message.");
                            } elseif ($status == 'sent') {
                                $meta_data = $whatsappLog->meta_data;
                                $meta_data['delivered_at'] = Carbon::now()->toDayDateTimeString();
                                $whatsappLog->meta_data = $meta_data;
                                $whatsappLog->status = (string) CommunicationStatusEnum::DELIVERED->value;
                            }
                            $whatsappLog->save();
                        }
                    }  
                }
            }
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'error'   => $e->getMessage(),
            ], 500);
        }
        
    }
}