73 lines
2.3 KiB
Go
73 lines
2.3 KiB
Go
package erp
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"strings"
|
|
)
|
|
|
|
// Webhook headers. Frappe's Webhook doctype signs the JSON body with
|
|
// HMAC-SHA256 and sends it base64-encoded in X-Frappe-Webhook-Signature;
|
|
// the mock adds X-Frappe-Event-Id so receipts are idempotent by id.
|
|
const (
|
|
HeaderSignature = "X-Frappe-Webhook-Signature"
|
|
HeaderEventID = "X-Frappe-Event-Id"
|
|
HeaderEvent = "X-Frappe-Event"
|
|
)
|
|
|
|
// Webhook events the registry maps onto the tenant ladder (ERP/02).
|
|
const (
|
|
EventSalesOrderSubmit = "sales_order.submit"
|
|
EventInvoiceOverdue = "sales_invoice.overdue"
|
|
EventPaymentEntrySubmit = "payment_entry.submit"
|
|
EventSubscriptionCancel = "subscription.cancel"
|
|
)
|
|
|
|
// WebhookEvent is the payload shape both the mock and the live Frappe
|
|
// Webhook configuration (ERP/03) deliver.
|
|
type WebhookEvent struct {
|
|
Event string `json:"event"`
|
|
Doctype string `json:"doctype"`
|
|
Name string `json:"name"`
|
|
Modified string `json:"modified,omitempty"`
|
|
Customer string `json:"customer,omitempty"`
|
|
TenantID string `json:"tenant_id,omitempty"`
|
|
Items []WebhookItem `json:"items,omitempty"`
|
|
DaysOverdue int `json:"days_overdue,omitempty"`
|
|
Subscription string `json:"subscription,omitempty"`
|
|
Invoice string `json:"invoice,omitempty"`
|
|
Amount float64 `json:"amount,omitempty"`
|
|
}
|
|
|
|
type WebhookItem struct {
|
|
ItemCode string `json:"item_code"`
|
|
Qty float64 `json:"qty"`
|
|
}
|
|
|
|
// Sign returns the base64 HMAC-SHA256 of body.
|
|
func Sign(secret string, body []byte) string {
|
|
mac := hmac.New(sha256.New, []byte(secret))
|
|
mac.Write(body)
|
|
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
|
|
}
|
|
|
|
// VerifySignature accepts the Frappe base64 form and the GitHub-style
|
|
// "sha256=<hex>" form.
|
|
func VerifySignature(secret string, body []byte, header string) bool {
|
|
header = strings.TrimSpace(header)
|
|
if secret == "" || header == "" {
|
|
return false
|
|
}
|
|
mac := hmac.New(sha256.New, []byte(secret))
|
|
mac.Write(body)
|
|
sum := mac.Sum(nil)
|
|
if hexSig, ok := strings.CutPrefix(header, "sha256="); ok {
|
|
want, err := hex.DecodeString(hexSig)
|
|
return err == nil && hmac.Equal(want, sum)
|
|
}
|
|
want, err := base64.StdEncoding.DecodeString(header)
|
|
return err == nil && hmac.Equal(want, sum)
|
|
}
|