POST encripted request with JSON body on R

扶醉桌前 提交于 2019-12-24 00:46:33

问题


I am trying to use R to post an encrypted request to an API.

Specifically the /v3/orders/ request.

It requires the use of an API key and secret, as well as an increasing nonce.

Using openssl, jsonlite and httr libraries:

The body has to be JSON encoded:

book<-"btc_eth"
side<-"sell"
major<-"0.1"
price<-"100"
type<-"limit"

Payload<-toJSON(data.frame(book=book,side=side,major=major,price=price,type=type))

It also requires an authorization header constructed with an sha256 encrypted signature.

N<-NONCE() # "1503033312"

method<-"POST"

Path<-"/v3/orders/"

Signature<-sha256(paste0(N,method,Path,Payload),secret)

header<-paste0("Bitso ",key,":",N,":",Signature)

Finally the request should look like this:

url<-"https://api.bitso.com/v3/orders/"

r<-POST(url, body = Payload, add_headers(Authorization=header))

I have been able to post requests with an empty payload to this API before, but this call sends unsupported media type error, something about the way I'm JSON encoding the paylod is causing this.

There's Ruby and PHP examples on how to place this request here.


回答1:


As I haven't got a key to try, this is an answer from a case I was once face to — you might want to change a little bit you JSON call. toJSON puts a bracket at each side of you call. So you need to remove them :

# Go from
Payload<- jsonlite::toJSON(data.frame(book=book,side=side,major=major,price=price,type=type))
Payload
[{"book":"btc_eth","side":"sell","major":"0.1","price":"100","type":"limit"}] 

# To
Payload <- gsub("\\[|\\]", "", Payload)
Payload
{"book":"btc_eth","side":"sell","major":"0.1","price":"100","type":"limit"}

Let me know if it works,

Best,

Colin




回答2:


So, I finally was able to send the request.

I have to thank Colin Fay for his response on how to eliminate the brackets.

The thing was, the header had to be constructed with the unbracketed JSON body, but the body had to be sent as a list with automatic JSON encoding as following:

NC<-NONCE()

mthd<-"POST"

Pyld<- toJSON(data.frame(book=book,side=side,major=major,price=price,type=type))

Pyld <- gsub("\\[|\\]", "", Pyld)

body<-list(book=book,side=side,major=major,price=price,type=type)

url<-"https://api.bitso.com/v3/orders/"

Pth<-"/v3/orders/"

hdr<-paste0("Bitso ",ky,":",NC,":",sha256(paste0(NC,mthd,Pth,Pyld),scrt))

r<-POST(url, body = body, add_headers(Authorization=hdr),encode="json",verbose())


来源:https://stackoverflow.com/questions/45749105/post-encripted-request-with-json-body-on-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!