Integração

API de WhatsApp para Go

Integre WhatsApp em serviços Go usando apenas a biblioteca padrão.

package whatsapp

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"time"
)

type mensagem struct {
	Instance string `json:"instance"`
	Number   string `json:"number"`
	Text     string `json:"text"`
}

type resposta struct {
	Success   bool   `json:"success"`
	MessageID string `json:"messageId"`
}

var cliente = &http.Client{Timeout: 30 * time.Second}

func EnviarTexto(instancia, numero, texto string) (string, error) {
	corpo, err := json.Marshal(mensagem{instancia, numero, texto})
	if err != nil {
		return "", err
	}

	req, err := http.NewRequest(
		http.MethodPost,
		"https://zapixo.com.br/api/v1/messages/text",
		bytes.NewReader(corpo),
	)
	if err != nil {
		return "", err
	}

	req.Header.Set("Authorization", "Bearer "+os.Getenv("ZAPIXO_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	res, err := cliente.Do(req)
	if err != nil {
		return "", err
	}
	defer res.Body.Close()

	if res.StatusCode != http.StatusOK {
		return "", fmt.Errorf("zapixo respondeu %d", res.StatusCode)
	}

	var r resposta
	if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
		return "", err
	}
	return r.MessageID, nil
}