Last active
July 12, 2020 10:47
-
-
Save cayter/82c04d526e28475a65ff3a5c084d5022 to your computer and use it in GitHub Desktop.
Rapyd's Go Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"crypto/hmac" | |
"crypto/sha256" | |
"encoding/base64" | |
"encoding/hex" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"math/rand" | |
"net/http" | |
"strconv" | |
"strings" | |
"time" | |
) | |
var ( | |
baseURL = "https://sandboxapi.rapyd.net" | |
accessKey = "<YOUR_ACCESS_KEY>" | |
secretKey = "<YOUR_SECRET_KEY>" | |
) | |
func main() { | |
rand.Seed(time.Now().Unix()) | |
resp, err := request("POST", "/v1/payments", []byte("")) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// Unmarshal `resp` into struct... | |
} | |
func request(method, path string, body []byte) ([]byte, error) { | |
salt := strconv.Itoa(rand.Intn(10000000000)) | |
timestamp := strconv.FormatInt(time.Now().Unix(), 10) | |
toSign := strings.ToLower(method) + path + salt + timestamp + accessKey + secretKey + string(body) | |
toSignHmac := hmac.New(sha256.New, []byte(secretKey)) | |
_, err := toSignHmac.Write([]byte(toSign)) | |
if err != nil { | |
return nil, err | |
} | |
signature := base64.StdEncoding.EncodeToString([]byte(hex.EncodeToString(toSignHmac.Sum(nil)))) | |
headers := map[string]string{ | |
"content-type": "application/json", | |
"salt": salt, | |
"signature": signature, | |
"timestamp": timestamp, | |
} | |
req, err := http.NewRequest(method, baseURL+path, bytes.NewBuffer(body)) | |
if err != nil { | |
return nil, err | |
} | |
for k, v := range headers { | |
req.Header.Set(k, v) | |
} | |
client := &http.Client{} | |
resp, err := client.Do(req) | |
if err != nil { | |
return nil, err | |
} | |
defer resp.Body.Close() | |
return ioutil.ReadAll(resp.Body) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment