Akilan Arasu Akilan Arasu - 16 days ago 9
iOS Question

WooCommerce iOS OAuth Invalid Signature

Many people have been tearing their hair out looking for a solution to the invalid signature issue when sending requests to the WooCommerce api from an iOS app.

I have put together the solution here.

Answer

I am providing the solution for the invalid signature issue when sending requests to the WooCommerce API from an iOS app.

To use WooCommerce in the iOS app, the requests must authenticate using OAuth 1.0. In iOS, regardless of whether the app is being written in Objective-C or Swift, AFNetworking makes life easier when writing requests.

Follow this procedure to setup your requests:

  1. Get the URL, OAuth 1.0 Consumer key and consumer secret ready.
  2. Add AFNetworking to your project using Cocoapods. Your podfile will look like this:

      source 'https://github.com/CocoaPods/Specs.git'
      platform :ios, '9.0'
    
      target 'OAuthSample3' do
          use_frameworks!
    
          # Pods for OAuthSample3
          pod 'AFNetworking', '1.3.4'
      end
    

    Save this in your project directory and run pod install in terminal.
    For the next step, we must install AFNetworking 1.3.4. That's why it says 1.3.4 in the podfile.

  3. Next, download this project from github: https://github.com/khanghoang/-WooClient
    Unzip it and copy AFOAuth1Client.h, AFOAuth1Client.m, AFOAuth1OneLeggedClient.h, AFOAuth1OneLeggedClient.m, AFOAuth1OneLeggedClientWooParser.h, AFOAuth1OneLeggedClientWooParser.m to your project.

  4. Now we need to modify these files a bit. Open AFOAuth1Client.h and find the AFHMACSHA1Signature() method.
    Look for these lines:

      // one-legged
      if(![secret isEqualToString:@""]) {
          secretString = [secretString stringByAppendingFormat:@"&%@", AFPercentEscapedQueryStringPairMemberFromStringWithEncoding(secret, stringEncoding)];
      }  
    

    And replace them with:

      // one-legged  
      secretString = [secretString stringByAppendingFormat:@"&"];  
    
  5. That's it! This will solve the issue.

In your view controller you could make the request like this:

- (void)viewDidLoad {
    [super viewDidLoad];

    AFOAuth1OneLeggedClient *client = [[AFOAuth1OneLeggedClient alloc] initWithBaseURL:[NSURL URLWithString:PATH] key:OAUTH_CONSUMER_KEY secret:OAUTH_CONSUMER_SECRET];

    [client getPath:@"orders" parameters:@{} success:^(AFHTTPRequestOperation *operation, id responseObject) {



        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];
}  

You could add parameters in the dictionary. The OAUTH_CONSUMER_KEY and OAUTH_CONSUMER_SECRET must be replaced by the values you gathered in the first step.

You could also do this in Swift. Just use a bridging header to import the AFNetworking files.

Many thanks to khanghoang for the breakthrough in AFOAuth1Client.

Comments