Skip to content

Instantly share code, notes, and snippets.

@jpillora
Created April 27, 2016 02:02
Show Gist options
  • Save jpillora/e8edc1cb83033baf13aa998422ee7843 to your computer and use it in GitHub Desktop.
Save jpillora/e8edc1cb83033baf13aa998422ee7843 to your computer and use it in GitHub Desktop.
Xero API for Private applications in Go (golang)
package main
import (
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/garyburd/go-oauth/oauth"
)
const (
XeroRequestTokenURL = "https://api.xero.com/oauth/RequestToken"
XeroAuthorizeTokenURL = "https://api.xero.com/oauth/Authorize"
XeroAccessTokenURL = "https://api.xero.com/oauth/AccessToken"
XeroApiEndpointURL = "https://api.xero.com/api.xro/2.0/"
)
func main() {
//parse your private key (see http://developer.xero.com/documentation/getting-started/private-applications/)
path := "/path/to/my/xero-private.pem"
pemBytes, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal(err)
}
block, extra := pem.Decode(pemBytes)
if block == nil || len(extra) > 0 {
log.Fatal("Failed to decode PEM")
}
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
log.Fatal(err)
}
//create the oauth1 client using this key (consumer secret not required)
client := oauth.Client{
Credentials: oauth.Credentials{Token: "Z0TXP197I4IEXAMPLE1234"},
TemporaryCredentialRequestURI: XeroRequestTokenURL,
ResourceOwnerAuthorizationURI: XeroAuthorizeTokenURL,
TokenRequestURI: XeroAccessTokenURL,
SignatureMethod: oauth.RSASHA1,
PrivateKey: privateKey,
Header: http.Header{"Accept": []string{"application/json"}}, //noone likes XML
}
//list all invoices
response, err := client.Get(http.DefaultClient, &client.Credentials, XeroApiEndpointURL+"invoices/", nil)
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
//show response
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(contents))
}
@spyqs
Copy link

spyqs commented Oct 23, 2018

how do you add query parameters? I get an error when trying to do so, for example: InvoiceReference="xxx"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment