Currently I am using Salesforce's rest api so that I can create and update objects in Salesforce.
By using curl command, I could find out that I can create and update the objects in salesforce as I wanted them to be.
Now I want to create a method that can do the same as I did with curl command. But it seems like I need to do something in order for the authorization as I read the error below.
#<Net::HTTPUnauthorized:0x000055a3702171e0>%
what I want to do is something like this.
1, I want to create the objects in salesforce.
2, to update objects I need Account obejcts.
3, so I want to create a method that extracts all Account objects from salesforce.
4, in a method I need to send Http request with access_token.
5, but I don't know how to set the access_token.
this is the curl command I tried for authentication and to get Account objects
OAuth
curl -v https://test.salesforce.com/services/oauth2/token \
-d "grant_type=password" \
-d "client_id=3MasubgboasbboUIUBOBOUBOUBOJBUTFHBLKJHIU1rMmmDExvMtiR" \
-d "client_secret=D33ASDFAS82C0EASDFAS48E8F1C21ASFASW6EF21C4D7AASDF4EB5EF3" \
-d "username=MYNAME@COMPANY.co.jp.instance" -d "password=yatta-"
get Account curl "https://instance.my.salesforce.com//services/data/v52.0/sobjects/Account" -H "Authorization: Bearer 00D1s0023202345234pwb!AQQasdgas3eOlKbprFFRMT_SLFp.Pwt5Q07AI0uHasdgasdxmasdgas2nLiaZ.baVoLZvVVaQK"
get Account
curl "https://instance.my.salesforce.com//services/data/v52.0/sobjects/Account" -H "Authorization: Bearer 00D1s0023202345234pwb\!AQQasdgas3eOlKbprFFRMT_SLFp.Pwt5Q07AI0uHasdgasdxmasdgas2nLiaZ.baVoLZvVVaQK"
the code I tried is something like this.
def get_salesforce_company_list
#γhit api and get company list
access_token = auth
uri = URI.parse("https://instance.my.salesforce.com//services/data/v52.0/sobjects/Account")
request = Net::HTTP::Get.new(uri)
request["Authorization"] = "Bearer" + access_token
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
print response
end
def auth
uri = URI.parse("https://test.salesforce.com/services/oauth2/token")
request = Net::HTTP::Post.new(uri)
request.set_form_data(
"client_id" => "jnas;jdbojasn;djlnfalsjbdbkjbljasdasknl",
"client_secret" => "asjbdabHVIVHBJNFLNLKNJDNSjbljsg",
"grant_type" => "password",
"password" => "yatta-",
"username" => "Myname@COMPANY.co.jp.INSTANCE",
)
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
auth_info = JSON.parse(response.body)
auth_info["access_token"]
end
If anyone knows how to send http request or any ideas how to solve this, I would really appreciate.
EDITS
in the code above, "auth" method works fine and I can get the access_token correctly. the problem is that I can't set it to the "get_salesforce_company_list" method and use it as bearer token.
Thank you.