Wire SendPulse newsletter signup into waitlist endpoint, add subscriber to address book 568090

This commit is contained in:
Patrick Britton 2026-02-06 14:45:51 -06:00
parent b91e42d005
commit 90ff6e223b

View file

@ -1,7 +1,11 @@
package main package main
import ( import (
"bytes"
"context" "context"
"encoding/json"
"fmt"
"io"
"net/http" "net/http"
"os" "os"
"os/signal" "os/signal"
@ -189,12 +193,17 @@ func main() {
c.JSON(400, gin.H{"error": "Valid email required"}) c.JSON(400, gin.H{"error": "Valid email required"})
return return
} }
// Store locally
_, err := dbPool.Exec(c.Request.Context(), _, err := dbPool.Exec(c.Request.Context(),
`INSERT INTO public.waitlist (email) VALUES ($1) ON CONFLICT (email) DO NOTHING`, req.Email) `INSERT INTO public.waitlist (email) VALUES ($1) ON CONFLICT (email) DO NOTHING`, req.Email)
if err != nil { if err != nil {
c.JSON(500, gin.H{"error": "Failed to join waitlist"}) c.JSON(500, gin.H{"error": "Failed to join waitlist"})
return return
} }
// Add to SendPulse in background
go func(email string) {
addToSendPulse(cfg, email)
}(req.Email)
c.JSON(200, gin.H{"message": "You're on the list!"}) c.JSON(200, gin.H{"message": "You're on the list!"})
}) })
} }
@ -457,3 +466,55 @@ func main() {
log.Info().Msg("Server exiting") log.Info().Msg("Server exiting")
} }
func addToSendPulse(cfg *config.Config, email string) {
if cfg.SendPulseID == "" || cfg.SendPulseSecret == "" {
return
}
// 1. Get OAuth token
tokenBody, _ := json.Marshal(map[string]string{
"grant_type": "client_credentials",
"client_id": cfg.SendPulseID,
"client_secret": cfg.SendPulseSecret,
})
tokenResp, err := http.Post("https://api.sendpulse.com/oauth/access_token", "application/json", bytes.NewReader(tokenBody))
if err != nil {
log.Error().Err(err).Msg("SendPulse: failed to get token")
return
}
defer tokenResp.Body.Close()
var tokenData struct {
AccessToken string `json:"access_token"`
}
if err := json.NewDecoder(tokenResp.Body).Decode(&tokenData); err != nil || tokenData.AccessToken == "" {
log.Error().Err(err).Msg("SendPulse: failed to parse token")
return
}
// 2. Add subscriber to Sojorn Waitlist (address book 568090)
subBody, _ := json.Marshal(map[string]interface{}{
"emails": []map[string]string{
{"email": email},
},
})
req, _ := http.NewRequest("POST", "https://api.sendpulse.com/addressbooks/568090/emails", bytes.NewReader(subBody))
req.Header.Set("Authorization", "Bearer "+tokenData.AccessToken)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Error().Err(err).Msg("SendPulse: failed to add subscriber")
return
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
body, _ := io.ReadAll(resp.Body)
log.Error().Str("status", fmt.Sprintf("%d", resp.StatusCode)).Str("body", string(body)).Msg("SendPulse: add subscriber failed")
return
}
log.Info().Str("email", email).Msg("SendPulse: subscriber added to waitlist")
}