Authorize.net payment gateway Charge a Credit Card API for iOS swift - ios

hello everyone as i am using payment gateway charge credit api but i am getting error while passing json object to api.and here my original JSON object which pass to charge credit api.
{
"createTransactionRequest": {
"merchantAuthentication": {
"name": "XXXXXX",
"transactionKey": "XXXXXXXX"
},
"refId": "123456",
"transactionRequest": {
"transactionType": "authCaptureTransaction",
"amount": "5",
"payment": {
"creditCard": {
"cardNumber": "5424000000000015",
"expirationDate": "2020-12",
"cardCode": "999"
}
}
}
}
}
this is original json request
but in iOS while making JSON we get below JSON object and sequence of JSON object are change that's why we getting error from api.
{
"createTransactionRequest": {
"merchantAuthentication": {
"name": "XXXXXX",
"transactionKey": "XXXXXXX"
},
"refId": "123456",
"transactionRequest": {
"amount": "5",
"payment": {
"creditCard": {
"cardCode": "999",
"cardNumber": "5424000000000015",
"expirationDate": "2020-12"
}
},
"transactionType": "authCaptureTransaction"
}
}
}
after passing this JSON object to API, we will get bellow error
{
"messages": {
"resultCode": "Error",
"message": [
{
"code": "E00003",
"text": "The element 'transactionRequest' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd' has invalid child element 'amount' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'. List of possible elements expected: 'transactionType' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'."
}
]
}
}
here is my code for creating JSON object in app
var dict = Dictionary<String, Any>()
dict=[
"merchantAuthentication": [
"name": "xxxxxxx",
"transactionKey": "xxxxxxx"
],
"refId": "5656",
"transactionRequest": [
"transactionType": "authCaptureTransaction",
"amount": "55",
"payment": [
"creditCard": [
"cardNumber": "4111111111111111",
"expirationDate": "2020-12",
"cardCode": "999"
]
]
]
]
after print this JSON sequence are changed

Have you read the documentation? It's very clear from the linked page that what you're running into is a side effect of their translation of JSON elements to XML elements in the backend, specifically around the ordering of parameters in your JSON request:
A Note Regarding JSON Support
The Authorize.Net API, which is not
based on REST, offers JSON support through a translation of JSON
elements to XML elements. While JSON does not typically require a set
order to the elements in an object, XML requires strict ordering.
Developers using the Authorize.Net API should force the ordering of
elements to match this API Reference.
Their examples below this block also show that their transactionType parameters appear as the first attribute in the transactionRequest object. Tl;dr - move your transactionType parameter up in your transactionRequest object:
{
"createTransactionRequest": {
"merchantAuthentication": {
"name": "XXXXXX",
"transactionKey": "XXXXXXX"
},
"refId": "123456",
"transactionRequest": {
"transactionType": "authCaptureTransaction",
"amount": "5",
"payment": {
"creditCard": {
"cardCode": "999",
"cardNumber": "5424000000000015",
"expirationDate": "2020-12"
}
}
}
}
}

please try with following code.
let merchantSub = ["name": "XXXXXX",
"transactionKey": "XXXXXXX"]
let childCreditCard = ["cardCode": "999",
"cardNumber": "5424000000000015",
"expirationDate": "2020-12"]
let creditCard = ["creditCard":childCreditCard]
let transactionRequest = ["amount": "",
"payment":creditCard,
"transactionType":""] as [String : Any]
let merchantAuthentication = ["merchantAuthentication" :merchantSub,
"refId" : "123456",
"transactionRequest":transactionRequest] as [String : Any]
let param = ["createTransactionRequest" : merchantAuthentication]
if let data = try? JSONSerialization.data(withJSONObject: param, options: .prettyPrinted),
let str = String(data: data, encoding: .utf8) {
print(str)
}
However I recommend to use class but for initial level do like this.

Related

Titanium- Post request is not working when I using JSONArray in body content

Hi I am sending POST request using HTTPClient. Here I am passing some JSON data which have some arrays.
{
"pccpId": "11111",
"courseId": "XXXXX",
"employeeId": "XXXXXX",
"userId": "X!##$",
"assignments": [
{
"Id": "XXXX",
"targetDate": "05/30/2018",
"targetNewDate": "04/30/2018"
},
{
"Id": "YYYYY",
"targetDate": "04/22/2018",
"targetNewDate": "04/26/2018"
}
]
}
When I am using this data, I am getting 400 error code. When I am checking with backend is not at all hitting to the server. Same data giving expected result when I run on Postman.
Anyone have any suggestion!!
Thanks
I have this pb with titanium nodeJS api, workaround is to stringify your data and parse it on server
Try to but your keys without double quotation like this
{
pccpId: "11111",
courseId: "XXXXX",
employeeId: "XXXXXX",
userId: "X!##$",
assignments: [{
"Id": "XXXX",
"targetDate": "05/30/2018",
"targetNewDate": "04/30/2018"
},
{
"Id": "YYYYY",
"targetDate": "04/22/2018",
"targetNewDate": "04/26/2018"
}
]
}

Parse JSON with Swift JSON

How to get Value Radio Name With Swift JSON
I wrote like this
let response = JSON["topradio"]["Data"]
before this i created model for values but am not able to pic values like radio_name
{
"topradio": {
"result": "success",
"Data": [
[
{
"radio_name": "Kantipur",
"rimage": "radio/1422960479145155755920731096211441695162.jpeg",
"status": "1",
"user_faverate": "false",
"popular_radio": "0",
"radio_id": "4"
}
]
[
{
"radio_name": "Kantipur",
"rimage": "radio/1422960479145155755920731096211441695162.jpeg",
"status": "1",
"user_faverate": "false",
"popular_radio": "0",
"radio_id": "4"
}
]
]
}
Thanks in Advance
You can iterate through your nested data Array this way.
let dataArray = JSON["topradio"]["Data"].array
for item in dataArray {
let itemArray = item.array
for subItem in itemArray {
if let name = subItem["radio_name"].string {
print(name)
}
}
}

Get key of dictionary on JSON parse with SwiftyJSON

I want to get "key of dictionary" (that's what I called, not sure if it is right name) on this JSON
{
"People": {
"People with nice hair": {
"name": "Peter John",
"age": 12,
"books": [
{
"title": "Breaking Bad",
"release": "2011"
},
{
"title": "Twilight",
"release": "2012"
},
{
"title": "Gone Wild",
"release": "2013"
}
]
},
"People with jacket": {
"name": "Jason Bourne",
"age": 15,
"books": [
{
"title": "Breaking Bad",
"release": "2011"
},
{
"title": "Twilight",
"release": "2012"
},
{
"title": "Gone Wild",
"release": "2013"
}
]
}
}
}
First of all, I already created my People struct that will be used to map from those JSON.
Here is my people struct
struct People {
var peopleLooks:String?
var name:String?
var books = [Book]()
}
And here is my Book struct
struct Book {
var title:String?
var release:String?
}
From that JSON, I created engine with Alamofire and SwiftyJSON that will be called in my controller via completion handler
Alamofire.request(request).responseJSON { response in
if response.result.error == nil {
let json = JSON(response.result.value!)
success(json)
}
}
And here is what I do in my controller
Engine.instance.getPeople(request, success:(JSON?)->void),
success:{ (json) in
// getting all the json object
let jsonRecieve = JSON((json?.dictionaryObject)!)
// get list of people
let peoples = jsonRecieve["People"]
// from here, we try to map people into our struct that I don't know how.
}
My question is, how to map my peoples from jsonRecieve["People"] into my struct?
I want "People with nice hair" as a value of peopleLooks on my People struct. I thought "People with nice hair" is kind of key of dictionary or something, but I don't know how to get that.
Any help would be appreciated. Thank you!
While you iterate through dictionaries, for instance
for peeps in peoples
You can access key with
peeps.0
and value with
peeps.1
You can use key, value loop.
for (key,subJson):(String, JSON) in json["People"] {
// you can use key and subJson here.
}

Swift 3 looping JSON data

I'm attempting to loop through a JSON array sending data to a struct.
Here's my code that uses SwiftyJSON to return a JSON object:
performAPICall() {
json in
if(json != nil){
print("Here is the JSON:")
print(json["content"]["clients"])
let clients = json["content"]["clients"]
for client in clients {
var thisClient = Client()
thisClient.id = client["id"].string
thisClient.desc = client["desc"].string
thisClient.name = client["name"].string
self.clientArray.append(thisClient)
}
self.tableView.reloadData()
} else {
print("Something went very wrong..,")
}
}
I'm not quite sure why I'm getting "has no subscript" errors on the three strings.
Any help appreciated, thanks.
EDIT: Here's a sample of the JSON
{
"content": {
"clients": [{
"group": "client",
"id": "group_8oefXvIRV4",
"name": "John Doe",
"desc": "John's group."
}, {
"group": "client",
"id": "group_hVqIc1eEsZ",
"name": "Demo Client One",
"desc": "Demo Client One's description! "
}, {
"group": "client",
"id": "group_Yb0vvlscci",
"name": "Demo Client Two",
"desc": "This is Demo Client Two's group"
}]
}
}
You should use array method. Thus, your line
let clients = json["content"]["clients"]
should use array (and unwrap it safely):
guard let clients = json["content"]["clients"].array else {
print("didn't find content/clients")
return
}
// proceed with `for` loop here

SwiftyJSON Issue

I'm using Alamofire to get data from an API. I'm using SwiftyJSON to parse the JSON response. Currently, I'm iterating through product data and want to extract product details and display them in a collection view. The issue is, I can't seem to figure out how to access each product in the array. Here's the array that's returned:
{
"1": {
"product_id": 2982493187,
"merged_status": "TRUE",
"merged": [
{
"id": 2982493187,
"title": "Waves Eclipse Tee in Black",
"handle": "waves-eclipse-tee-in-black",
"published_at": "2015-10-09T21:00:50-07:00",
"published_scope": "global",
}
]
}
},
{
"2": {
"product_id": 2982432131,
"merged_status": "TRUE",
"merged": [
{
"id": 2982432131,
"title": "Waves Eclipse Tee in Off White",
"handle": "waves-eclipse-tee-in-off-white",
"published_at": "2015-10-09T21:00:50-07:00",
"published_scope": "global",
}
]
}
}
For each of these products I want to access the product_id. I'm trying to do so like so: productArray[0]["produdct_id"].int, but it doesn't seem to work. Any ideas?
You do not have an array in your results, but a dictionary with keys of "1", "2", etc.
let product_id = result["1"]["product_id"].int
It seems that the result json is an array of dictionary, so you can access the product_id via
let product_id = result[0]["1"]["product_id"].int
Try this:
let jsonProductsArray = JSON(theRawJSONData).array
for (key, productJSON):(String, JSON) in jsonProductsArray {
print(key);
let product_id = productJSON["product_id"].int
print(product_id)
}

Resources