// // EbayWebServiceManager.swift // Vendoo // // Created by Okechi Onyeje on 6/3/16. // Copyright © 2016 Okechi Onyeje. All rights reserved. // import Foundation import Locksmith protocol EbayWebServiceManagerDelegate { func signInUser(string: String!) } class EbayWebServiceManager: NSObject { //API Manager class variables //----------------------------------------------// let baseURL = "https://api.sandbox.ebay.com/ws/api.dll" private var apiKey: String! private var devKey: String! private var certID: String! private var mutableData: NSMutableData = NSMutableData() private var currentElementName:NSString = "" private var userEmail:String = (NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)! private var signinURL: String! private var xmlResponseDictionary: Dictionary = Dictionary() var delegate: EbayWebServiceManagerDelegate? var isAuthorized: Bool = NSUserDefaults.standardUserDefaults().boolForKey("ebayAuthorized") //let tradingClient = EBayTradingServiceClient.sharedClient() //---------------------------------------------// //let tradingClient = SOAPEngine() override init(){ super.init() // self.tradingClient.debug = true if let path = NSBundle.mainBundle().pathForResource("Services", ofType: "plist"), dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] { self.apiKey = ((dict["Ebay"] as! Dictionary)["consumerKey"] as! String) self.devKey = ((dict["Ebay"] as! Dictionary)["devID"] as! String) self.certID = ((dict["Ebay"] as! Dictionary)["CertID"] as! String) self.signinURL = ((dict["Ebay"] as! Dictionary)["signin"] as! String) if(self.isAuthorized){ let dictionary = Locksmith.loadDataForUserAccount(self.userEmail, inService: "vendoo_oauth_ebay") self.xmlResponseDictionary["eBayAuthToken"] = dictionary?["ebay_oauth"] as? String } /* tradingClient.userAgent = "SOAPEngine" tradingClient.actionNamespaceSlash = true tradingClient.version = SOAPVersion.VERSION_1_1 tradingClient.responseHeader = true tradingClient.header = "967"+"" + self.devKey + "" + "" + self.certID + "" + "GetSessionID" tradingClient.setIntegerValue(967, forKey: "X-EBAY-API-COMPATIBILITY-LEVEL") //tradingClient.setValue(self.devKey, forKey: "X-EBAY-API-DEV-NAME") //tradingClient.setValue(tradingClient.apiKey, forKey: "X-EBAY-API-APP-NAME") tradingClient.setIntegerValue(0, forKey: "X-EBAY-API-SITEID") //tradingClient.setValue(self.certID, forKey: "X-EBAY-API-CERT-NAME") //tradingClient.setValue("GeteBayOfficialTime", forKey: "X-EBAY-API-CALL-NAME") tradingClient.envelope = "xmlns=\"urn:ebay:apis:eBLBaseComponents\"" tradingClient.authorizationMethod = SOAPAuthorization.AUTH_TOKEN tradingClient.requestURL(self.baseURL, soapAction: self.baseURL+"GetSessionID", completeWithDictionary: {(statusCode : Int, dict : [NSObject : AnyObject]!) -> Void in print(statusCode) let result:Dictionary = dict as Dictionary NSLog("%@", result) }, failWithError: {(error : NSError!) -> Void in NSLog("%@", error) }) */ /*tradingClient.requestURL(baseURL, soapAction: baseURL+"/GetSessionID", completeWithDictionary: {(statusCode : Int, dict : [NSObject : AnyObject]!) -> Void in let result:Dictionary = dict as Dictionary NSLog("%@", result) }, failWithError: {(error : NSError!) -> Void in NSLog("%@", error) })*/ } } } //MARK: - authentication methods extension EbayWebServiceManager { private func requestMaker(soapMessage: String!, theRequest: NSMutableURLRequest!) { let msgLength = soapMessage.characters.count theRequest.addValue("text/xml", forHTTPHeaderField: "Content-Type") theRequest.addValue(String(msgLength), forHTTPHeaderField: "Content-Length") theRequest.addValue("967", forHTTPHeaderField: "X-EBAY-API-COMPATIBILITY-LEVEL") theRequest.addValue(self.devKey, forHTTPHeaderField: "X-EBAY-API-DEV-NAME") theRequest.addValue(self.certID, forHTTPHeaderField: "X-EBAY-API-CERT-NAME") theRequest.addValue(self.apiKey, forHTTPHeaderField: "X-EBAY-API-APP-NAME") theRequest.addValue("0", forHTTPHeaderField: "X-EBAY-API-SITEID") theRequest.addValue("", forHTTPHeaderField: "SOAPAction") theRequest.HTTPMethod = "POST" theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) // or false let connection = NSURLConnection(request: theRequest, delegate: self, startImmediately: true) connection!.start() if (connection == true) { var mutableData : Void = NSMutableData.initialize() } } func authorizeApp(){ let soapMessage = "" + "" + "Kroleo-Kroleo-Vendoo-S-ktqeobkk" + "" let url = NSURL(string: self.baseURL) let theRequest = NSMutableURLRequest(URL: url!) theRequest.addValue("GetSessionID", forHTTPHeaderField: "X-EBAY-API-CALL-NAME") self.requestMaker(soapMessage, theRequest: theRequest) } func deauthorizeApp(){ let soapMessage = "" + "" + "" + "\(self.xmlResponseDictionary["eBayAuthToken"])" + "​" let url = NSURL(string: self.baseURL) let theRequest = NSMutableURLRequest(URL: url!) theRequest.addValue("RevokeToken", forHTTPHeaderField: "X-EBAY-API-CALL-NAME") self.requestMaker(soapMessage, theRequest: theRequest) //delete token from locksmith keychain do{ try Locksmith.deleteDataForUserAccount(self.userEmail, inService: "vendoo_oauth_ebay") print("account credentials deleted for ebay") NSUserDefaults.standardUserDefaults().setBool(false, forKey: "ebayAuthorized") self.isAuthorized = false } catch{ (error) print(error) //could not save data to keychain print("account credentials could not be deleted") } } func listItem(){ } func fetchToken() { let soapMessage = "" + "\(self.xmlResponseDictionary["SessionID"] as! String!)" let url = NSURL(string: self.baseURL) let theRequest = NSMutableURLRequest(URL: url!) theRequest.addValue("FetchToken", forHTTPHeaderField: "X-EBAY-API-CALL-NAME") self.requestMaker(soapMessage, theRequest: theRequest) } } extension EbayWebServiceManager: NSURLConnectionDelegate { func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) { mutableData.length = 0; print(response) } func connection(connection: NSURLConnection!, didReceiveData data: NSData!) { mutableData.appendData(data) print(data) } func connectionDidFinishLoading(connection: NSURLConnection!) { let response = NSString(data: mutableData, encoding: NSUTF8StringEncoding) print(response) let xmlParser = NSXMLParser(data: mutableData) xmlParser.delegate = self xmlParser.parse() xmlParser.shouldResolveExternalEntities = true } func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) { challenge.sender!.performDefaultHandlingForAuthenticationChallenge!(challenge) } } extension EbayWebServiceManager: NSXMLParserDelegate { func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { currentElementName = elementName } func parser(parser: NSXMLParser, foundCharacters string: String) { switch (self.currentElementName) { case "SessionID": self.xmlResponseDictionary["SessionID"] = string var str = "\(signinURL)&SessID=\(string)" self.signinURL = str print(self.signinURL) print((self.currentElementName as String) + " : " + string) self.delegate?.signInUser(self.signinURL) break case "eBayAuthToken": self.xmlResponseDictionary["eBayAuthToken"] = string print(string) //save token to locksmith keychain do{ try Locksmith.saveData(["ebay_oauth" : string], forUserAccount: self.userEmail, inService: "vendoo_oauth_ebay") print("account credentials saved") NSUserDefaults.standardUserDefaults().setBool(true, forKey: "ebayAuthorized") self.isAuthorized = true //Test authentication let soapmessage = "" + "" + "\(string)" + "" let url = NSURL(string: self.baseURL) let theRequest = NSMutableURLRequest(URL: url!) theRequest.addValue("GeteBayOfficialTime", forHTTPHeaderField: "X-EBAY-API-CALL-NAME") self.requestMaker(soapmessage, theRequest: theRequest) } catch{ (error) print(error) //could not save data to keychain print("account credentials could not be saved") } break case "HardExpirationTime" : print(string) break default: //print(string) print("\(self.currentElementName):\(string)") } } }