Trying to connect Magento 1.9 using REST API and Scribe-Java 1.3.7
Done creating Web Services Role and Consumer as below:
After that, run the following codes:
public final class MagentoThreeLeggedOAuth extends DefaultApi10a {
private static final String BASE_URL = "http://my.magentoshop.com/";
#Override
public String getAccessTokenEndpoint() {
return BASE_URL + "oauth/token";
}
#Override
public String getAuthorizationUrl(Token requestToken) {
return BASE_URL + "admin/oauth_authorize?oauth_token="
+ requestToken.getToken(); //this implementation is for admin roles only...
}
#Override
public String getRequestTokenEndpoint() {
return BASE_URL + "oauth/token";
}
public static class Main {
public static void main(String[] args) {
final String MAGENTO_API_KEY = "[xxxxxxxxx]";
final String MAGENTO_API_SECRET = "[yyyyyyyyyy]";
final String MAGENTO_REST_API_URL = "http://my.magentoshop.com/api/rest";
// three-legged oauth
OAuthService service = new ServiceBuilder()
.provider(MagentoThreeLeggedOAuth.class)
.apiKey(MAGENTO_API_KEY).apiSecret(MAGENTO_API_SECRET).debug()
.build();
// start
Scanner in = new Scanner(System.in);
System.out.println("Magento's OAuth Workflow");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
Token requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println();
// Obtain the Authorization URL
System.out.println("Fetching the Authorization URL...");
String authorizationUrl = service.getAuthorizationUrl(requestToken);
System.out.println("Got the Authorization URL!");
System.out.println("Now go and authorize Main here:");
System.out.println(authorizationUrl);
System.out.println("And paste the authorization code here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
}
}
}
and below are the errors shown on console:
Magento's OAuth Workflow
Fetching the Request Token...
obtaining request token from http://my.magentoshop.com/oauth/token
setting oauth_callback to oob
generating signature...
using base64 encoder: CommonsCodec
base string is: POST&http%3A%2F%2Fmy.magentosgop.com%2Foauth%2Ftoken&oauth_callback%3Doob%26oauth_consumer_key%3Dxxxxxxxxxxxxxxxx%26oauth_nonce%3D2939370741%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1429517137%26oauth_version%3D1.0
signature is: nINxAFwv6woAAQYbdHn6v2Uc+lw=
appended additional OAuth parameters: { oauth_nonce -> 2939370741 , oauth_signature -> nINxAFwv6woAAQYbdHn6v2Uc+lw= , oauth_callback -> oob , oauth_consumer_key -> 20482d9e12ead3420a4c5aeb6978bf8e , oauth_timestamp -> 1429517137 , oauth_signature_method -> HMAC-SHA1 , oauth_version -> 1.0 }
using Http Header signature
sending request...
response status code: 400
response body: oauth_problem=parameter_absent&oauth_parameters_absent=oauth_token
Exception in thread "main" org.scribe.exceptions.OAuthException: Response body is incorrect. Can't extract token and secret from this: 'oauth_problem=parameter_absent&oauth_parameters_absent=oauth_token'
at org.scribe.extractors.TokenExtractorImpl.extract(TokenExtractorImpl.java:41)
at org.scribe.extractors.TokenExtractorImpl.extract(TokenExtractorImpl.java:27)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:64)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:40)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:45)
at MagentoThreeLeggedOAuth$Main.main(MagentoThreeLeggedOAuth.java:49)
What did I missed or wrongly done?
Thanks
OK, just found out the mistakes was:
Change this:
#Override
public String getRequestTokenEndpoint() {
return BASE_URL + "oauth/token";
}
To this:
#Override
public String getRequestTokenEndpoint() {
return BASE_URL + "oauth/initiate";
}
Related
Have one token generation API in one class which gives the below response.
{
"access_token": "eyJraWQiOiJNR2FOQUtYXC9pa0grNE1wTE9aS05wMGtqbXNOd0lzXC9WXC9EYm1LZ0pZdTZNPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIxYjBtcjc4cHNjMHIyM25nYnJqMml1MnNkNCIsInRva2VuX3VzZSI6ImFjY2VzcyIsInNjb3BlIjoic2dwZi5wcm9kdWN0XC",
"expires_in": 3600,
"token_type": "Bearer"
}
Then have another Get API in another class in which I want to extract this access_token value in the header in rest assured code. So how can I take that access token value in another class?
public class Get_Service_List {
private Response response;
String BaseUrl = "https://dev.api.sgf.eus.nt/pro";
#Given("Get Service list API")
public void get_Service_list_API() {
RestAssured.baseURI = BaseUrl;
}
#When("call the API with valid token and details")
public void call_the_API_with_valid_token_and_details() {
response = RestAssured.given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer "+TokenGeneration.accessToken)
.when()
.get("/api/protsvc/ser");
}
#Then("validate the resonse body with list of services")
public void validate_the_resonse_body_with_list_of_services() {
String response_body = response.getBody().asString();
System.out.println("response is: " +response_body);
}
#Then("validate for 200 status code")
public void validate_for_status_code() {
int status_code = response.getStatusCode();
System.out.println("status is: " +status_code);
}
}
I don't know much about how cucumber share state. Below is the way to extract access_token from response.
String accessToken = response.jsonPath().getString("access_token");
My goal is to create an aweber app that adds users to an email list I already have.
I currently have code that uses Oauth to get a token but this method also requires an aweber account users
to manually write their credentials in order to grant the app access. I would only ever be using my aweber 'app'
for my own purposes and I want to automate the process of authentication. Look for the comment "//going to the url manually here".
Thanks in advance for the help.
package aweber.test;
import java.util.Scanner;
import org.scribe.builder.ServiceBuilder;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
impo rt org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
public class AweberStuffTest
{
//To get your consumer key/secret, and view API docs, see https://labs.aweber.com/docs
private static final String ACCOUNT_RESOURCE_URL = "https://api.aweber.com/1.0/accounts/";
private static final String CONSUMER_KEY = "AkW******8QO0dMmmF";
private static final String CONSUMER_SECRET = "zfgmPsZkXBam6R***********YD";
public static void main(String[] args)
{
OAuthService service = new ServiceBuilder()
.provider(AWeberApi.class)
.apiKey(CONSUMER_KEY)
.apiSecret(CONSUMER_SECRET)
.build();
Scanner in = new Scanner(System.in);
System.out.println("=== AWeber's OAuth Workflow ===");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
Token requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println();
System.out.println("Now go and authorize Scribe here:");
String foo = service.getAuthorizationUrl(requestToken);
System.out.println(foo);
//going to the url manually here
System.out.println("And paste the verifier here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
Token accessToken = service.getAccessToken(requestToken, verifier);
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: " + accessToken + " )");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, ACCOUNT_RESOURCE_URL);
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with AWeber and Scribe! :)");
}
}
and
package aweber.test;
import org.scribe.builder.api.DefaultApi10a;
import org.scribe.model.Token;
public class AWeberApi extends DefaultApi10a
{
private static final String AUTHORIZE_URL = "https://auth.aweber.com/1.0/oauth/authorize?oauth_token=%s";
private static final String REQUEST_TOKEN_ENDPOINT = "https://auth.aweber.com/1.0/oauth/request_token";
private static final String ACCESS_TOKEN_ENDPOINT = "https://auth.aweber.com/1.0/oauth/access_token";
#Override
public String getAccessTokenEndpoint()
{
return ACCESS_TOKEN_ENDPOINT;
}
#Override
public String getRequestTokenEndpoint()
{
return REQUEST_TOKEN_ENDPOINT;
}
#Override
public String getAuthorizationUrl(Token requestToken)
{
return String.format(AUTHORIZE_URL, requestToken.getToken());
}
}
I need your help.
I need to connect to my Magento store using REST but I have a problem to retrieve the oauth token.
I did what was said in this tutorial : gmartinezgil.wordpress.com/2013/08/05/using-the-magento-rest-api-in-java-with-scribe/
My code is available here : https://www.dropbox.com/sh/zglzl9xsxcjrpid/lGrZNYfRzG
I'm working with Magento 1.8.1.0 using Wampserver
Here is my Main.java file:
package foo;
import java.util.Scanner;
import org.scribe.builder.*;
import org.scribe.builder.api.*;
import org.scribe.model.*;
import org.scribe.oauth.*;
/**
* #author jerry
*/
public final class Main {
/**
* #param args
*/
public static void main(String[] args) {
final String MAGENTO_API_KEY = "r0ntsryd0hamwmdnjezb8joun01c4h1s";
final String MAGENTO_API_SECRET = "czylgk8yxhkvrx141v1q9trx0iw4qbgt";
final String MAGENTO_REST_API_URL = "http://localhost/magento/api/rest/";
//final String MAGENTO_REST_API_URL = "http://localhost/magento/api.php?type=rest/";
// three-legged oauth
OAuthService service = new ServiceBuilder()
.provider(MagentoThreeLeggedOAuth.class)
.apiKey(MAGENTO_API_KEY)
.apiSecret(MAGENTO_API_SECRET)
.debug()
.build();
System.out.println("" + service.getVersion());
Scanner in = new Scanner(System.in);
System.out.println("Magento's OAuth Workflow");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
Token requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println();
System.out.println("Fetching the Authorization URL...");
String authorizationUrl = service.getAuthorizationUrl(requestToken);
System.out.println("Got the Authorization URL!");
System.out.println("Now go and authorize Main here:");
System.out.println(authorizationUrl);
System.out.println("And paste the authorization code here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
System.out.println("Trading the Request Token for an Access Token...");
Token accessToken = service.getAccessToken(requestToken, verifier);
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: "
+ accessToken + " )");
System.out.println();
OAuthRequest request = new OAuthRequest(Verb.GET, MAGENTO_REST_API_URL+ "/products?limit=2");
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println();
System.out.println(response.getCode());
System.out.println(response.getBody());
System.out.println();
}
}
The terminal displays :
1.0
Magento's OAuth Workflow
Fetching the Request Token...
obtaining request token from http://`magentohost`/oauth/initiate/
setting oauth_callback to oob
generating signature...
using base64 encoder: CommonsCodec
base string is: POST&http%3A%2F%2F127.0.0.1%2Fmagento%2Foauth%2Finitiate%2F&oauth_callback%3Doob%26oauth_consumer_key%3Dr0ntsryd0hamwmdnjezb8joun01c4h1s%26oauth_nonce%3D2085598405%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1395911858%26oauth_version%3D1.0
signature is: edOifgJQfBg2QoM7ifVBWwvYj30=
appended additional OAuth parameters: { oauth_callback -> oob , oauth_signature -> edOifgJQfBg2QoM7ifVBWwvYj30= , oauth_version -> 1.0 , oauth_nonce -> 2085598405 , oauth_signature_method -> HMAC-SHA1 , oauth_consumer_key -> r0ntsryd0hamwmdnjezb8joun01c4h1s , oauth_timestamp -> 1395911858 }
using Http Header signature
sending request...
response status code: 404
response body: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /magento/oauth/initiate/ was not found on this server.</p>
</body></html>
Exception in thread "main" org.scribe.exceptions.OAuthException: Response body is incorrect. Can't extract token and secret from this: '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /magento/oauth/initiate/ was not found on this server.</p>
</body></html>
'
at org.scribe.extractors.TokenExtractorImpl.extract(TokenExtractorImpl.java:41)
at org.scribe.extractors.TokenExtractorImpl.extract(TokenExtractorImpl.java:27)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:64)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:40)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:45)
at foo.Main.main(Main.java:35)
I think I found the solution. I activated mod_rewrite :http://www.webdevdoor.com/php/mod_rewrite-windows-apache-url-rewriting/ and did what is said here http://doc.prestashop.com/display/PS16/What+you+need+to+get+started and it worked.
I'm trying to write a simple Jenkins plug-in with integration with Box, but I always get this error:
=== Box's OAuth Workflow ===
Fetching the Authorization URL...
Got the Authorization URL!
Now go and authorize Scribe here:
https://www.box.com/api/oauth2/authorize?client_id=abc123&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fjenkins%2Fconfigure&response_type=code&state=authenticated
And paste the authorization code here
>>xyz9876543
Trading the Request Token for an Access Token...
Exception in thread "main" org.scribe.exceptions.OAuthException: Cannot extract an acces token. Response was: {"error":"invalid_request","error_description":"Invalid grant_type parameter or parameter missing"}
at org.scribe.extractors.JsonTokenExtractor.extract(JsonTokenExtractor.java:23)
at org.scribe.oauth.OAuth20ServiceImpl.getAccessToken(OAuth20ServiceImpl.java:37)
at com.example.box.oauth2.Box2.main(Box2.java:40)
Box2 class (for testing) :
public class Box2 {
private static final Token EMPTY_TOKEN = null;
public static void main(String[] args) {
// Replace these with your own api key and secret
String apiKey = "abc123";
String apiSecret = "xyz987";
OAuthService service = new ServiceBuilder().provider(BoxApi.class)
.apiKey(apiKey).apiSecret(apiSecret)
.callback("http://localhost:8080/jenkins/configure")
.build();
Scanner in = new Scanner(System.in);
System.out.println("=== Box's OAuth Workflow ===");
System.out.println();
// Obtain the Authorization URL
System.out.println("Fetching the Authorization URL...");
String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN);
System.out.println("Got the Authorization URL!");
System.out.println("Now go and authorize Scribe here:");
System.out.println(authorizationUrl);
System.out.println("And paste the authorization code here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: "
+ accessToken + " )");
System.out.println();
}
}
BoxApi class:
public class BoxApi extends DefaultApi20 {
private static final String AUTHORIZATION_URL =
"https://www.box.com/api/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code&state=authenticated";
#Override
public String getAccessTokenEndpoint() {
return "https://www.box.com/api/oauth2/token?grant_type=authorization_code";
}
#Override
public String getAuthorizationUrl(OAuthConfig config) {
return String.format(AUTHORIZATION_URL, config.getApiKey(),
OAuthEncoder.encode(config.getCallback()));
}
#Override
public Verb getAccessTokenVerb(){
return Verb.POST;
}
#Override
public AccessTokenExtractor getAccessTokenExtractor() {
return new JsonTokenExtractor();
}
}
I'm not sure how I get these exceptions. Can anyone who knows the Box API tell me if I've done anything wrong with it?
The request for the access token needs to be in the form of a POST request, with the parameters included in the body of the request–it looks like you're sending a GET with the parameters as URL parameters.
Here I want to get all contacts mail id of a person.
This code is redirecting to google site and after getting token and varifier it is returning status code and body which is printing on console.
I want to display response.getBody()(all maial contacts of a person) in jsp page.
How to do this?
public class googleOaoth extends ActionSupport {
private static final String NETWORK_NAME = "Google";
private static final String AUTHORIZE_URL = "https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token=";
private static final String PROTECTED_RESOURCE_URL = "https://www.google.com/m8/feeds/contacts/default/full";
private static final String SCOPE = "https://www.google.com/m8/feeds";
OAuthService service = new ServiceBuilder().provider(GoogleApi.class).apiKey("www.mysite").apiSecret("****").scope(SCOPE).callback("http://mysite/mypage").build();
Token requestToken;
private String url;
private String oauth_verifier;
private String oauth_token;
public String getOauth_verifier() {
return oauth_verifier;
}
public Token getRequestToken() {
return requestToken;
}
public void setRequestToken(Token requestToken) {
this.requestToken = requestToken;
}
public void setOauth_verifier(String oauth_verifier) {
this.oauth_verifier = oauth_verifier;
}
Map session = ActionContext.getContext().getSession();
//method which redirect to google page
public String LoginToGoogle() {
System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ===");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
setRequestToken(service.getRequestToken());
System.out.println("Got the Request Token!");
System.out.println("(if your curious it looks like this: " + getRequestToken() + " )");
System.out.println();
session.put("googleAccessToken", getRequestToken());
System.out.println("Now go and authorize Scribe here:");
setUrl(AUTHORIZE_URL + getRequestToken().getToken());
System.out.println(AUTHORIZE_URL + getRequestToken().getToken());
return "redirect";
}
//after getting varification code this method will show body and res_code
public String acceptToken() {
System.out.println("And paste the verifier here");
System.out.print(">>");
Verifier verifier = new Verifier(getOauth_verifier());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
//System.out.println("varifier : " + getOauth_verifier());
// System.out.println("token :" + getOauth_token());
//requestToken = service.getRequestToken();
setRequestToken((Token) session.get("googleAccessToken"));
System.out.println("token " + getRequestToken());
Token accessToken = service.getAccessToken(getRequestToken(), verifier);//requestToken
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: " + accessToken + " )");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
request.addHeader("GData-Version", "3.0");
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getCode());
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with Scribe! :)");
return SUCCESS;
}
Inside your action method create variable (e.g. respBody) with public getters/setters and assign response body to it.
respBody = response.getBody();
Then in JSP you can show it using <s:property> tag.
<s:property value="respBody"/>