an updated and hopefully faster version of the ST Toolbox
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

71 lines
1.8 KiB

package api
import (
"encoding/json"
"fmt"
"io"
"regexp"
)
func (s *Session) GetInvoice(identifier string) (map[string]interface{}, error) {
var endpoint string
isInvoiceNumber, _ := regexp.MatchString(`^[A-Za-z]`, identifier)
if isInvoiceNumber {
endpoint = fmt.Sprintf("/invoice?invoiceNumber=%s", identifier)
} else {
endpoint = fmt.Sprintf("/invoice/%s", identifier)
}
resp, err := s.DoRequest("GET", endpoint, nil)
if err != nil {
return nil, fmt.Errorf("error making request: %v", err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body: %v", err)
}
if resp.StatusCode == 403 {
// Handle 403 Forbidden specifically
return nil, fmt.Errorf("access forbidden: you may not have permission to view this invoice")
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("failed to get invoice info: %s", resp.Status)
}
var result map[string]interface{}
if err := json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("error unmarshalling response: %v", err)
}
// Log the entire response for debugging
// fmt.Printf("API Response: %+v\n", result)
if isInvoiceNumber {
// Handle invoice number case
data, ok := result["data"].(map[string]interface{})
if !ok {
return nil, nil // No invoice found
}
invoices, ok := data["invoices"].([]interface{})
if !ok || len(invoices) == 0 {
return nil, nil // No invoice found
}
invoice, ok := invoices[0].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("unexpected invoice structure")
}
return invoice, nil
} else {
// Handle invoice ID case
data, ok := result["data"].(map[string]interface{})
if !ok || len(data) == 0 {
return nil, nil // No invoice found
}
return data, nil
}
}