[英]curl post request in rails controller
我想将用curl(GoPay付款网关)编写的发帖请求转换为我的Rails应用程序:
curl -v https://gw.sandbox.gopay.com/api/oauth2/token \
-X "POST" \
-H "Accept: application/json" \
-H "Content-Type: application/x-www-form-urlencoded" \
-u "<Client ID>:<Client Secret>" \
-d "grant_type=client_credentials&scope=payment-create"
我正在尝试通过使用gem rest-client在rails控制器中进行操作。 我已经做过类似的事情,并且进行了很多次修改,但是无法正常工作:
RestClient::Request.execute( method: :post,
url: "https://gw.sandbox.gopay.com/api/oauth2/token",
"#{ENV['GOPAY_CLIENT_ID']}": "#{ENV['GOPAY_CLIENT_SECRET']}"
data: "grant_type=client_credentials&scope=payment-create"
)
我如何才能为其余客户端(或类似客户端)转换curl post请求?
编辑:它显示状态代码409:没有更多信息的冲突
EDIT1-rgo的修改后的代码有效,谢谢:
RestClient.post "https://#{ENV['GOPAY_CLIENT_ID']}:#{ENV['GOPAY_CLIENT_SECRET']}@gw.sandbox.gopay.com/api/oauth2/token",
{ grant_type: 'client_credentials', scope: 'payment-create'},
content_type: :json, accept: :json
我不是RestClient用户,但在阅读了文档[1]之后,我认为我将cURL请求转换为RestClient:
RestClient.post "http://#{ENV['GOPAY_CLIENT_ID']}:#{ENV['GOPAY_CLIENT_SECRET']}@https://gw.sandbox.gopay.com/api/oauth2/token",
{ grant_type: 'client_credentials', scope: 'payment-create'},
content_type: :json,
accept: :json
如您所见,由于是基本身份验证,因此我在URL中传递了凭据。 数据(grant_type和scope)作为哈希传递,然后转换为JSON。 然后,我们将rest客户端设置为发送和接收JSON。
希望对您有帮助
[1] https://github.com/rest-client/rest-client#usage-raw-url
您没有确切提到什么行不通或看到什么错误。 但是,curl的-u
选项用于传递基本身份验证的用户名和密码。
RestClient的等效项是使用user
和password
选项,例如
RestClient::Request.execute(
method: :post,
url: "https://gw.sandbox.gopay.com/api/oauth2/token",
user: "#{ENV['GOPAY_CLIENT_ID']}",
password: "#{ENV['GOPAY_CLIENT_SECRET']}"
data: "grant_type=client_credentials&scope=payment-create",
headers: { "Accept" => "application/json", "Content-Type" => "application/x-www-form-urlencode" }
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.