This commit is contained in:
cangui 2025-05-11 10:24:46 +02:00
parent 5cecc910b1
commit 5c8cce231d
3 changed files with 82 additions and 78 deletions

View File

@ -93,81 +93,7 @@ func SSOLoginHandler(db *gorm.DB) http.HandlerFunc {
http.Redirect(w, r, "/dashboard", http.StatusSeeOther)
}
}
func SendWhatsAppMessage(db *gorm.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
val := r.Context().Value("ssoid")
ssoid, ok := val.(string)
if !ok || ssoid == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
fmt.Println("✅ SSOID reçu depuis le contexte :", ssoid)
// Récupérer l'utilisateur en base via le SSOID
var user models.User
if err := db.Where("sso_id = ?", ssoid).First(&user).Error; err != nil || user.ID == 0 {
http.Error(w, "Utilisateur introuvable", http.StatusUnauthorized)
return
}
var payload map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
fmt.Printf("📨 Payload reçu : %+v\n", payload)
message, err := models.BuildMessageFromPayload(payload)
if err != nil {
http.Error(w, fmt.Sprintf("Error: %v", err), http.StatusBadRequest)
return
}
jsonBody, err := json.MarshalIndent(message, "", " ") // joli format
if err != nil {
http.Error(w, "Failed to encode message", http.StatusInternalServerError)
return
}
apiURL := fmt.Sprintf("https://graph.facebook.com/v22.0/%s/messages", user.WhatsappPhoneNumberID)
fmt.Println("📡 Envoi de la requête à :", apiURL)
fmt.Println("📦 JSON envoyé :")
fmt.Println(string(jsonBody))
req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(jsonBody))
if err != nil {
http.Error(w, "Failed to create request", http.StatusInternalServerError)
return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+user.WhatsappToken)
fmt.Println("📋 Headers :")
for key, vals := range req.Header {
for _, v := range vals {
fmt.Printf(" %s: %s\n", key, v)
}
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
http.Error(w, "Failed to contact WhatsApp API", http.StatusBadGateway)
return
}
defer resp.Body.Close()
// 🛠 debug réponse
respBody, _ := io.ReadAll(resp.Body)
fmt.Printf("✅ Réponse WhatsApp (%d) : %s\n", resp.StatusCode, string(respBody))
w.WriteHeader(resp.StatusCode)
w.Write(respBody)
}
}
var MessageTypeCreditCost = map[string]uint{
"text": 1,
@ -359,8 +285,8 @@ func WebhookReceiveHandler(db *gorm.DB) http.HandlerFunc {
MessageID: msgID,
Type: msgType,
Content: content,
Direction: "inbound",
Status: "received",
Direction: "Entrant",
Status: "Reçu",
ParentID: parentID,
}
@ -531,6 +457,81 @@ func HandleTemplateTest(db *gorm.DB) http.HandlerFunc {
json.NewEncoder(w).Encode(respBody)
}
}
func SendWhatsAppMessage(db *gorm.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
val := r.Context().Value("ssoid")
ssoid, ok := val.(string)
if !ok || ssoid == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
fmt.Println("✅ SSOID reçu depuis le contexte :", ssoid)
// Récupérer l'utilisateur en base via le SSOID
var user models.User
if err := db.Where("sso_id = ?", ssoid).First(&user).Error; err != nil || user.ID == 0 {
http.Error(w, "Utilisateur introuvable", http.StatusUnauthorized)
return
}
var payload map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
fmt.Printf("📨 Payload reçu : %+v\n", payload)
message, err := models.BuildMessageFromPayload(payload)
if err != nil {
http.Error(w, fmt.Sprintf("Error: %v", err), http.StatusBadRequest)
return
}
jsonBody, err := json.MarshalIndent(message, "", " ") // joli format
if err != nil {
http.Error(w, "Failed to encode message", http.StatusInternalServerError)
return
}
apiURL := fmt.Sprintf("https://graph.facebook.com/v22.0/%s/messages", user.WhatsappPhoneNumberID)
fmt.Println("📡 Envoi de la requête à :", apiURL)
fmt.Println("📦 JSON envoyé :")
fmt.Println(string(jsonBody))
req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(jsonBody))
if err != nil {
http.Error(w, "Failed to create request", http.StatusInternalServerError)
return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+user.WhatsappToken)
fmt.Println("📋 Headers :")
for key, vals := range req.Header {
for _, v := range vals {
fmt.Printf(" %s: %s\n", key, v)
}
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
http.Error(w, "Failed to contact WhatsApp API", http.StatusBadGateway)
return
}
defer resp.Body.Close()
// 🛠 debug réponse
respBody, _ := io.ReadAll(resp.Body)
fmt.Printf("✅ Réponse WhatsApp (%d) : %s\n", resp.StatusCode, string(respBody))
w.WriteHeader(resp.StatusCode)
w.Write(respBody)
}
}
func AdminUserDelete(db *gorm.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]

View File

@ -20,7 +20,7 @@
<script src="/frontend/assets/js/json-enc.js"></script>
<script src="/frontend/assets/js/ws.js"></script>
<script src="/frontend/assets/js/function/functions.js"></script>
<title>Login</title>
<title>Gestion WhatsApp</title>
</head>

View File

@ -1,3 +1,5 @@
{{ define "jwt.pages.tmpl" }}
{{ template "head" . }}
<!DOCTYPE html>
<html lang="fr">
<head>
@ -43,3 +45,4 @@
<button id="copyBtn" onclick="copyToken()" disabled>📋 Copier le token</button>
</body>
</html>
{{ end }}