2016-10-09 2 views
3

안녕하세요, 저는 현재 woocommerce API에서 작업 중이며, 저는 개조를 사용하여 API를 통합해야합니다. 웹 사이트는 입니다. HTTP입니다. HTTP는 기본 HTTP를 통해 차단할 수 있으므로 기본 HTTP를 사용할 수 없습니다. API는 OAuth 1.0a "one-legged"인증을 사용하여 API 키를 가로채는 것을 방지합니다. 나는 this artical을 통해 어떤 OAuth 메트로가 http에서 사용되는지 이해했습니다.woocomerce에 대한 개조를 사용하여 OAuth 1.0a를 구현하는 방법 안드로이드에있는 Api

Scribe을 사용하여 성공적으로 API를 구현했지만, 개조를 사용하여 API를 구현하고 싶습니다. 고글을 쓴 후에 Jake Wharton이 Oauth1SigningInterceptor 인 것으로 나타났습니다.

그래서 내가 인증을위한 개조하지만, API 호출의 반환에

{"code":"woocommerce_rest_cannot_view","message":"Sorry, you cannot list resources.","data":{"status":401}} 

내가 스크라이브를 사용하여 호출하면 동일한 API는 아래

내가 API를 호출하는 방법이다 성공적인 응답을 반환 것을 구현 (제이크 월튼 Oauth1SigningInterceptor에서 변성)

BasicAuthInterceptor.java

,
public class BasicAuthInterceptor implements Interceptor { 
private static final Escaper ESCAPER = UrlEscapers.urlFormParameterEscaper(); 
private static final String OAUTH_CONSUMER_KEY = "oauth_consumer_key"; 
private static final String OAUTH_NONCE = "oauth_nonce"; 
private static final String OAUTH_SIGNATURE = "oauth_signature"; 
private static final String OAUTH_SIGNATURE_METHOD = "oauth_signature_method"; 
private static final String OAUTH_SIGNATURE_METHOD_VALUE = "HMAC-SHA1"; 
private static final String OAUTH_TIMESTAMP = "oauth_timestamp"; 

private static final String OAUTH_VERSION = "oauth_version"; 
private static final String OAUTH_VERSION_VALUE = "1.0"; 

private final String consumerKey; 
private final String consumerSecret; 

private final Random random; 
private BasicAuthInterceptor(String consumerKey, String consumerSecret, Random random) { 
    this.consumerKey = consumerKey; 
    this.consumerSecret = consumerSecret; 

    this.random = random; 
} 
@Override 
public Response intercept(Chain chain) throws IOException { 
    return chain.proceed(signRequest(chain.request())); 
} 

public Request signRequest(Request request) throws IOException { 
    byte[] nonce = new byte[32]; 
    random.nextBytes(nonce); 
    String oauthNonce = ByteString.of(nonce).base64().replaceAll("\\W", ""); 
    String oauthTimestamp = String.valueOf(System.currentTimeMillis()); 

    String consumerKeyValue = ESCAPER.escape(consumerKey); 


    SortedMap<String, String> parameters = new TreeMap<>(); 
    parameters.put(OAUTH_CONSUMER_KEY, consumerKeyValue); 

    parameters.put(OAUTH_NONCE, oauthNonce); 
    parameters.put(OAUTH_TIMESTAMP, oauthTimestamp); 
    parameters.put(OAUTH_SIGNATURE_METHOD, OAUTH_SIGNATURE_METHOD_VALUE); 
    parameters.put(OAUTH_VERSION, OAUTH_VERSION_VALUE); 

    HttpUrl url = request.url(); 
    for (int i = 0; i < url.querySize(); i++) { 
     parameters.put(ESCAPER.escape(url.queryParameterName(i)), 
       ESCAPER.escape(url.queryParameterValue(i))); 
    } 


    RequestBody requestBody = request.body(); 
    Buffer body = new Buffer(); 

    if (requestBody != null) { 
     requestBody.writeTo(body); 
    } 

    while (!body.exhausted()) { 
     long keyEnd = body.indexOf((byte) '='); 
     if (keyEnd == -1) throw new IllegalStateException("Key with no value: " + body.readUtf8()); 
     String key = body.readUtf8(keyEnd); 
     body.skip(1); // Equals. 

     long valueEnd = body.indexOf((byte) '&'); 
     String value = valueEnd == -1 ? body.readUtf8() : body.readUtf8(valueEnd); 
     if (valueEnd != -1) body.skip(1); // Ampersand. 

     parameters.put(key, value); 
    } 

    Buffer base = new Buffer(); 
    String method = request.method(); 
    base.writeUtf8(method); 
    base.writeByte('&'); 
    base.writeUtf8(ESCAPER.escape(request.url().newBuilder().query(null).build().toString())); 
    base.writeByte('&'); 

    boolean first = true; 
    for (Map.Entry<String, String> entry : parameters.entrySet()) { 
     if (!first) base.writeUtf8(ESCAPER.escape("&")); 
     first = false; 
     base.writeUtf8(ESCAPER.escape(entry.getKey())); 
     base.writeUtf8(ESCAPER.escape("=")); 
     base.writeUtf8(ESCAPER.escape(entry.getValue())); 
    } 

    String signingKey = 
      ESCAPER.escape(consumerSecret);// + "&" + ESCAPER.escape(accessSecret); 

    SecretKeySpec keySpec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1"); 
    Mac mac; 
    try { 
     mac = Mac.getInstance("HmacSHA1"); 
     mac.init(keySpec); 
    } catch (NoSuchAlgorithmException | InvalidKeyException e) { 
     throw new IllegalStateException(e); 
    } 
    byte[] result = mac.doFinal(base.readByteArray()); 
    String signature = ByteString.of(result).base64(); 

    String authorization = "OAuth " 
      + OAUTH_CONSUMER_KEY + "=\"" + consumerKeyValue + "\", " 
      + OAUTH_NONCE + "=\"" + oauthNonce + "\", " 
      + OAUTH_SIGNATURE + "=\"" + ESCAPER.escape(signature) + "\", " 
      + OAUTH_SIGNATURE_METHOD + "=\"" + OAUTH_SIGNATURE_METHOD_VALUE + "\", " 
      + OAUTH_TIMESTAMP + "=\"" + oauthTimestamp + "\", " 

      + OAUTH_VERSION + "=\"" + OAUTH_VERSION_VALUE + "\""; 

    Log.d("message","--"+authorization); 


    return request.newBuilder() 
      .addHeader("Authorization", authorization) 
    .addHeader("Content-Type", "application/json;charset=UTF-8") 
    .addHeader("Accept", "application/json;versions=1") 
      .build(); 
} 

public static final class Builder { 
    private String consumerKey; 
    private String consumerSecret; 

    private Random random = new SecureRandom(); 


    public Builder consumerKey(String consumerKey) { 
     if (consumerKey == null) throw new NullPointerException("consumerKey = null"); 
     this.consumerKey = consumerKey; 
     return this; 
    } 

    public Builder consumerSecret(String consumerSecret) { 
     if (consumerSecret == null) throw new NullPointerException("consumerSecret = null"); 
     this.consumerSecret = consumerSecret; 
     return this; 
    } 



    public Builder random(Random random) { 
     if (random == null) throw new NullPointerException("random == null"); 
     this.random = random; 
     return this; 
    } 



    public BasicAuthInterceptor build() { 
     if (consumerKey == null) throw new IllegalStateException("consumerKey not set"); 
     if (consumerSecret == null) throw new IllegalStateException("consumerSecret not set"); 

    } 
} 
} 

원격 API 호출

public final class RemoteApiCalls { 
private static final String TAG = "RemoteApiCalls"; 

public static final class Builder { 
    RemoteRetrofitInterfaces mService; 
    Retrofit mRetrofit; 

    public Builder remoteApiCall(String url,Context mContext) { 
     return remoteApiCall(mContext,url, 40, 40, 40); 
    } 

    BasicAuthInterceptor oauth1 = new BasicAuthInterceptor.Builder() 
      .consumerKey("keyhere")//i have added keys 
      .consumerSecret("secert here")//i have added secertkeys 
      .build(); 

    public Builder remoteApiCall(Context mContext, String url, int connectionTimeout, int readTimeout, int writeTimeout) { 

     HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); 
     interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); 
     OkHttpClient client = new OkHttpClient.Builder() 
       .connectTimeout(20, TimeUnit.SECONDS) 
       .writeTimeout(20, TimeUnit.SECONDS) 
       .readTimeout(30, TimeUnit.SECONDS).addInterceptor(interceptor).addInterceptor(oauth1) 
       .build(); 

     mRetrofit = new Retrofit.Builder() 
       .baseUrl(url).addConverterFactory(GsonConverterFactory.create()) 
       .client(client) 
       .build(); 
     mService = mRetrofit.create(RemoteRetrofitInterfaces.class); 


     return this; 
    } 



    public void getProductCatogry() 

    { 

     Call<ProductCategoryResponse> mApiCall = mService.getListCategory(); 
     mApiCall.enqueue(new Callback<ProductCategoryResponse>() { 
      @Override 
      public void onResponse(Call<ProductCategoryResponse> call, Response<ProductCategoryResponse> response) { 

       if (response.isSuccessful()) { 


       } else { 

       } 
      } 

      @Override 
      public void onFailure(Call<ProductCategoryResponse> call, Throwable t) { 
t.printStackTrace(); 
      } 


     }); 

    } 

} 

} 

RemoteRetrofitInterfaces.java

내가

new RemoteApiCalls.Builder().remoteApiCall("http://mywebsite.com/wp-json/wc/v1/",getApplicationContext()).getProductCatogry(); 
전화의 주요 활동에
public interface RemoteRetrofitInterfaces { 

@GET("products") 
Call<ProductCategoryResponse> getListCategory(); 
} 

여전히 401 오류

{"code":"woocommerce_rest_cannot_view","message":"Sorry, you cannot list resources.","data":{"status":401}} 
을 얻고있다 사용

우 상거래 버전은 버전 2.6.4 API 버전은 어느 날 내가 개조 자체와이를 구현하려면이 문제를 해결하는 데 도움이 될 수 있습니다 V1

입니다 .

답변

2

마지막으로 내가 솔루션이 다른

내가 여러 문서

1) Using the WooCommerce REST API – Introduction

2) woocommerce-rest-api-docs

3) Scribe

4 통과 도움이되기를 바랍니다 발견) scribe:1.3.5

위의 문서와 소스 코드를 참조한 후 OAuth 1을 수행하는 라이브러리를 만들었습니다.안드로이드 woocommerce의 HTTP에 대한 0A "한 다리"인증

전체 설명을 여기에 도서관

WoocommerceAndroidOAuth1 LIBRARY

을 확인 내 라이브러리

의 날을 읽을 섹션에 추가했습니다