HTTP Stripe Request Not Going Through [Swift] - php

I am currently linking my IOS app with the backend to process Stripe payments. I am using FileZilla to host the files, and cSpan to host the server. Here is my swift code:
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, errorD -> Void in
if errorD == nil {
print("got response")
do {
let jsonResult: NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
let jsonComp = jsonResult?.value(forKey: "completion") as! String
print(jsonComp)
} catch {
print(errorD?.localizedDescription)
// ERROR OCCURS HERE
}
//let jsonResult: Any! = JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
// print(jsonResult)
} else {
print("error")
}
}) task.resume()
And here is a screenshot of my FileZilla directory:
(I just realized that the picture doesn't actually show the file 'token.php' in the Payments directory, but it is there.)
As you can see, I am properly going into the correct directory to get to the file, and performing the right methods to get complete the HTTP request. What is strange, however, is that it will always cause an error after the 'catch', but it will display nil when I try to print the localized description of the error. Here is the php code inside of token.php
<?php
require_once('stripe-php/init.php');
\Stripe\Stripe::setApiKey("sk_test_eRFc0VoIi7mo7zBuArrznB5a");
// Get the credit card details submitted by the form
$token = $_POST['stripeToken'];
$amount = $_POST['amount'];
$type = $_POST['type'];
$name = $_POST['name'];
// Create the charge on Stripe's servers - this will charge the user's card
try {
$charge = \Stripe\Charge::create(array(
"amount" => $amount,
"currency" => "usd",
"source" => $token,)
);
//email the purcahse and code info to your email
mail("willcohen2000#gmail.com","Purchase done","amount: $amount , type: $type, name: $name");
// create a json output with completion variable, (this will be read from the ios app as response)
$json = array(
'completion' => 'done'
);
echo json_encode($json);
} catch(\Stripe\Error\Card $e) {
// The card has been declined
$errorMessage = $e->getMessage();
$json = array(
'completion' => $getMessage()
);
echo json_encode($json);
}
?>
As it may be a bit evident, I am relatively inexperienced at backend work, so any explanation or point in the correct direction will be highly appreciated. Thanks.

Related

Create managed stripe account with php and swift

so I'm trying to create managed stripe accounts with PHP Swift and Alamofire. But it's not working at all.
Here's my PHP code:
<?php
require_once('vendor/autoload.php');
\Stripe\Stripe::setApiKey("My APIKEY");
$country = $_POST['country'];
$create = \Stripe\Account::create(array(
"country" => $country,
"managed" => true
)
);
?>
Here's my swift code:
#IBAction func createBtn(_ sender: Any) {
let card = STPCardParams()
card.number = "5200828282828210"
card.expMonth = 4
card.expYear = 2024
card.cvc = "242"
card.currency = "usd"
STPAPIClient.shared().createToken(withCard: card ,completion: {(token, error) -> Void in
if let error = error {
print("ERROR: \(error.localizedDescription)")
}
else if let token = token {
print(token)
self.createUsingToken(token:token)
}
})
}
func createUsingToken(token:STPToken) {
let requestString = "My request URL"
let params = ["token": token.tokenId, "country": "US"]
//This line of code will suffice, but we want a response
Alamofire.request(requestString, method: .post, parameters: params).responseJSON { (response) in
print("REQUEST: \(response.request!)") // original URL request
print("RESPONSE: \(response.response!)") // URL response
print("DATA: \(response.data!)") // server data
print("RESULT: \(response.result)") // result of response serialization
if let JSON = response.result.error {
print("JSON: \(JSON.localizedDescription)")
}
}
}
And I'm getting this error from Alamofire: JSON: Response could not be serialized, input data was nil or zero length.
Thanks for your help.
It looks like your Swift/Alamofire request is expecting a JSON response, but your PHP code is not sending any response at all: you're sending an account creation request to Stripe but then never outputting any data.
You likely want to prepare an array with the attributes that you expect in your Swift code, then output it as JSON at the end of your PHP script:
echo json_encode($result);

POST data from iOS to php server always NULL - iOS 10, Swift 3, php

i am implementing a FCM app server and wanted to store the device registration token id into my own database (Server written in PHP).
I realise the data in device id token is always null, Can someone point the right way to store the token accordingly into database?
Really appreciated perhaps someone could guide me on this issue, thanks!
Kindly refer the code/screenshots below:-
AppDelegate.swift
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
var token = ""
for i in 0..<deviceToken.count {
token += String(format: "%02.2hhx", arguments: [deviceToken[i]])
}
print("Registration succeeded!")
print("Token: ", token)
Callquery(token)
}
AppDelegate.swift (Callquery method which send a POST request to server side script)
func Callquery(_ token: String)
{
// append parameter to oneDictionary
let tokenString = ["token": token] as [String: Any]
// create the request
var request = URLRequest(url: URL(string:"https://YourURL.com/admin/registerToken.php")!)
// set the method as POST
request.httpMethod = "POST"
// append the paramter to body
request.httpBody = try! JSONSerialization.data(withJSONObject: tokenString, options: [])
// create the session
URLSession.shared.dataTask(with:request, completionHandler: {(data, response, error) in
if error != nil {
print("There was error during datatask session")
print(error)
} else {
do {
guard let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] else { return }
guard let errors = json?["errors"] as? [[String: Any]] else { return }
if errors.count > 0 {
// show error
print("There is an error during parse JSON datatask")
return
} else {
// show confirmation
print("datatask with JSON format performed successfully")
}
}
}
print(request)
}).resume()
}
Service Side Script(registerToken.php):
<?php
include 'config.php';
$token = $_POST['token'];
$sql = "INSERT INTO users (email,device_id) VALUES ('email','$token')";
mysqli_query($conn, $sql);
mysqli_close($conn);
?>
Running App with real devices log as below:-
Database users table (device id always has nothing):-
users table structure:-
tokenString :-
I had solved this issue by using GET method instead of POST method as below:-
Appdelegate.swift :
var request = URLRequest(url: URL(string:"https://YourURL.com/admin/registerToken.php?token=\(token)")!)
Server side script :
$token = $_GET['token'];

Invalid JSON require Swift iOS

I am developing a simple iOS Swift app. I want to make a log-in screen for my app that will connect to already existing user database in Wordpress. I found some PHP scripts and Swift code.
I am trying to post username and login, check it and return the result(isUser = true/false or 1/0)
Here is a PHP script
<?php
// Read request parameters
$username= $_REQUEST["username"];
$password = $_REQUEST["password"];
// Store values in an array
$returnValue = array("username"=>$username, "password"=>$password);
// Send back request in JSON format
echo json_encode($returnValue);
?>
and a Swift function
func getPHPJson() {
let urlPath: String = "LINK_TO_PHP_FILE?username=\(user)&password=\(pass)"
let url: NSURL = NSURL(string: urlPath)!
let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "GET"
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
do
{
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary
{
print(jsonResult)
//print(jsonResult["isUser"] as! Bool)
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("raw response: \(responseString!)")
}
} catch let error as NSError
{
print(error.localizedDescription)
print("error")
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("raw response: \(responseString)")
}
})
}
it gives me a desired result.
OUTPUT
{
password = iosappusettest1;
username = iosappusettest;
}
raw response: {"username":"iosappusettest","password":"iosappusettest1"}
But when I add function to check if user is registered - I always get an invalid JSON
here is PHP function
function authentication ($user, $pass){
global $wp, $wp_rewrite, $wp_the_query, $wp_query;
if(empty($user) || empty($pass)){
return 0;
} else {
require_once('../wp-blog-header.php');
$status = 0;
$auth = wp_authenticate($user, $pass );
if( is_wp_error($auth) ) {
$status = 0;
} else {
$status = 1;
}
return $status;
}
}
I believe the problem is require_once function. In raw response I get a lot of html tags and other data that make my JSON invalid.
Is there any way to clear the page and output in the JSON only? echo "<script> document.documentElement.innerHTML = ''; </script>"; in PHP did't help me. maybe jQuery will help?
Maybe I can check if user is registered in another way?
Maybe I can store my result in a separate place or temp file?
Maybe I should wrap my data not in JSON but something else?
So I need to pass username and password to PHP, check it with authentication function(that uses require_once) and send back the $status to iOS Swift app ass variable.
Question is answered.
The problem was in WP plugin, that redirected all unlogined users from all the links in that domain, so when i called require_once('../wp-blog-header.php'); i was always redirected to main page and that was the reason for wrong JSON file with all the HTML markup.
Keep your response in pure JSON, and leave out any html tags as they are not needed by your ios end.

Stripe API (PHP) & Parse

I am building an app on iOS in swift and I am accepting payments using stripe. I have created a form that creates a customer and upon a successful save I call back the customerID and save it into my Parse Database.
Below is the code for the above:
XCODE:
let myCustomerID = user!.valueForKey("secretID") as! String
self.sendTokenToServer(myCustomerID, myAmount: cost)
func sendTokenToServer(aCustomer: String, myAmount: String) {
var theamount = myAmount
// SEND REQUEST TO PHP FILE IN WEBSERVER
let url = NSURL(string: ".../cutomeragain.php")
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
let body = "custID=\(aCustomer)&amount=\(theamount)"
request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
// SEND ASYNCHORNOUS REQUEST
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
(response, data, error) -> Void in
if error == nil {
}
}
When I go to charge the customer by ID, it does not accept the charge. Below is the PHP code:
<?php
require_once('stripe-php/init.php');
\Stripe\Stripe::setApiKey('xxx');
// Get the credit card details submitted by the form
$amount = $_POST['amount'];
$customerId = $_POST['custID'];
$cutomer = \Stripe\Customer::retrieve('custID');
// Charge the Customer instead of the card
$charge = \Stripe\Charge::create(array(
"amount" => $amount,
"currency" => "usd",
"customer" => $customerId)
);
// create a json output with completion variable, (this will be read from the ios app as response)
$json = array(
'completion' => 'done',
'completion1' => $cutomerId,
'ok' => $cutomer-id
);
echo json_encode($json);
?>
Am I missing something in my PHP file? I've tried a number of different methods. I.e. retrieving the customer from Stripe using
Ok so I figured it out. I had to play around a bit, however, I think that someone else will find this useful.
In my xcode file I changed
let myCustomerID = user!.valueForKey("secretID") as! String
to
let myCustomerID = user?["secretID"] as? String
In my PHP file I changed the code to the following:
// Get the credit card details submitted by the form
$amount = $_POST['amount'];
$customerId = $_POST['cus'];
$cu = \Stripe\Customer::retrieve($customerId);
// Charge the Customer instead of the card
$charge = \Stripe\Charge::create(array(
"amount" => $amount,
"currency" => "usd",
"customer" => $customerId,)
);
// create a json output with completion variable, (this will be read from the ios app as response)
$json = array(
'completion' => 'done',
'completion1' => $cutomerId,
'ok' => $cutomer-id
);
echo json_encode($json);
?>

Swift Invalid value around character 0

i need help with my app login code.
I try to make a Http Request to my local server, a simple login request with mail and password but i've a issue and i don't know how to fix it.
#IBAction func clickConnexionBtn(sender: AnyObject)
{
if(!mailTf.text!.isEmpty && !passwordTf.text!.isEmpty)
{
let mail = mailTf.text!
let password = passwordTf.text!
let param = String(format: "mail=%#&password=%#", arguments: [mail, password]);
let url = NSURL(string: "http://localhost:8888/MoneyManager/login.php")!
RequestObject.sharedInstance.prepareRequest(param, _url: url, _method: "POST")
let task = NSURLSession.sharedSession().dataTaskWithRequest(RequestObject.sharedInstance.request)
{ data, response, error in
if error != nil
{
let alertView = UIAlertController(title: "Error server", message: "Could not connect to server", preferredStyle: UIAlertControllerStyle.Alert)
self.showViewController(alertView, sender: self)
}
else
{
let serverResponse = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Server response: \(serverResponse)")
do
{
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as? NSDictionary {
print(json)
}
} catch let error2 as NSError {
print(error2.description)
}
}
}
task.resume()
}
}
So this is the action when i click on the 'connexionButton'.
Unfortunately when i try to Serialize the JSON, i have this error:
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
My PHP code is like:
if($result)
{
$return = array("Success" => 1, "Message" => "Insert user done", "user_id" => $_SESSION['id'], "api_key" => $_SESSION['api_key']);
echo json_encode($return);
}
Here is the code of my 'print("Server ....")'
Server response: Optional(Connexion successfully {"Success":1,"Message":"Insert user done","user_id":"9","api_key":"aa3b0c16fc63efe207be1a7471ac234a"})
Its all the data that i want to get and turn into JSON object
I look many subject but no one of them could help me cause most of the people use Alamofire to perform request.
So please if you have an idea, i listening
Thanks all.

Categories