Chris Stahl Chris Stahl - 3 months ago 19
Objective-C Question

I have an iOS app written in Objective-c and a Wordpress Website with WooCommerce. How can I connect them?

I built a website and set it up with the WooCommerce plugin to handle my eCommerce. That system works great.

I built an iOS app that is not connected to my Wordpress site at all. I am clearly a novice, but I am trying to understand how to connect these two systems.

Usernames/Passwords, Purchases, Shipping, etc....

Can anyone point me in the right direction of a solution, because I am coming up blank on my search. Thanks!

Answer

Step 1) Install one of the plugins for Wordpress authentication. (P.S. I used basic authentication in the example below.)

Step 2) Go to WooCommerce > Settings > API > Keys/Apps, and add a new key and then generate API Key. It will create consumer_key and consumer_secret for you.

Step 3) Enable REST API in the WooCommerce settings. (To enable the REST API within WooCommerce, visit the WooCommerce > Settings > API tab and tick the Enable REST API checkbox.) source

Step 4) I assume that you are developing an app with Swift. If so see the code below for getting user details and orders for example. Don't forget to include Alamofire framework in your project.

// to get user info
let plainString = "WP_username:WP_password" as NSString
let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))


let headers = [
    "Authorization": "Basic " + base64String
]

Alamofire.request(.GET, "http://yourwebsite.com/wp-json/wp/v2/users/me?_envelope=1&context=embed", headers: headers)
    .responseJSON{ response in switch response.result {
    case .Success(let JSON):
        print("Success with JSON: \(JSON)")

    case .Failure(let error):
        print("Request failed with error: \(error)")
        }
}


// to get a customer's orders
Alamofire.request(.GET, "https://yourwebsite.com/wc-api/v3/customers/USER_ID/orders", parameters:    
["consumer_key":"ck_XXX", "consumer_secret":"cs_XXX"])
         .responseJSON{ response in switch response.result {
            case .Success(let JSON):
                let response = JSON as! NSDictionary
                print(response)

            case .Failure(let error):
                print("Request failed with error: \(error)")
          }
}