Zaif API for Google Apps Script

Gists

This sample script is for using Zaif API by Google Apps Script.

The following go script is a sample at Zaif API.

package main

import (
    "fmt"
    "time"
    "strconv"
    "crypto/hmac"
    "crypto/sha512"
    "io/ioutil"
    "net/http"
    "encoding/hex"
    "net/url"
    "strings"
)

var key = "<your_key>"
var secret = "<your_secret>"

func main() {

    uri := "https://api.zaif.jp/tapi"
    values := url.Values{}
    values.Add("method", "get_info")
    values.Add("nonce", strconv.FormatInt(time.Now().Unix(), 10))

    encodedParams := values.Encode()
    req, _ := http.NewRequest("POST", uri, strings.NewReader(encodedParams))

    hash := hmac.New(sha512.New, []byte(secret))
    hash.Write([]byte(encodedParams))
    signature := hex.EncodeToString(hash.Sum(nil))

    req.Header.Add("Key", key)
    req.Header.Add("Sign", signature)
    client := new(http.Client)
    resp, _ := client.Do(req)
    defer resp.Body.Close()

    byteArray, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(byteArray))
}

When this is converted to GAS, the script is as follows.

function main(){
  var key = "### your key ###";
  var secret = "### your secret ###";

  var nonce = (new Date().getTime() / 1000).toFixed(0);
  var params = "method=get_info&nonce=" + nonce;
  var sign = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, params, secret);
  sign = sign.map(function(e) {return ("0" + (e & 0xFF).toString(16)).slice(-2)}).join("");
  var options = {
    method: "post",
    headers: {
      "key": key,
      "sign": sign
    },
    muteHttpExceptions: true
  };
  var res = UrlFetchApp.fetch("https://api.zaif.jp/tapi", options);
  Logger.log(res.getContentText())
}