I'm very new to development and couldn't find much end to end support on this topic. I did what I could using firebase help page.
I'm unable to receive notifications on my ios devices but FCM is working perfectly on android.
Here is my appdelegate from xcode
import UIKit
import Firebase
import FirebaseMessaging
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UIApplication.shared.applicationIconBadgeNumber = 0
// Override point for customization after application launch.
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
// For iOS 10 data message (sent via FCM)
//FIRMessaging.messaging().remoteMessageDelegate = self
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
UIApplication.shared.registerForRemoteNotifications()
}
application.registerForRemoteNotifications()
FirebaseApp.configure()
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token1 = Messaging.messaging().fcmToken
print("FCM token: \(token1 ?? "")")
var request = URLRequest(url: URL(string: "http://www.myurl.com/register.php")!)
request.httpMethod = "POST"
let postString = "Token="+token1!
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
}
task.resume()
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Registration failed!")
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (_ options: UNNotificationPresentationOptions) -> Void) {
// custom code to handle push while app is in the foreground
print("Handle push from foreground\(notification.request.content.userInfo)")
let dict = notification.request.content.userInfo["aps"] as! NSDictionary
let d : [String : Any] = dict["alert"] as! [String : Any]
let body : String = d["body"] as! String
let title : String = d["title"] as! String
// print("Title:\("FOSG NOTIFICATION") + body:\(body)")
self.showAlertAppDelegate(title: "Federation Of Safety Glass",message:body,buttonTitle:"ok",window:self.window!)
}
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
// if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background
print("Handle push from background or closed\(response.notification.request.content.userInfo)")
}
func showAlertAppDelegate(title: String,message : String,buttonTitle: String,window: UIWindow){
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.default, handler: nil))
window.rootViewController?.present(alert, animated: false, completion: nil)
}
// Firebase ended here
}
and this is my code from server end on php
$tokens = array(); $mess = '';
// queries from db to set the values of variables.
function send_notification ($tokens, $message)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'registration_ids' => $tokens,
'data' => $message
);
$headers = array(
'Authorization:key = **key ',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
$message = array(
"body" => $mess,
"message" => $mess,
"title" => "FOSG NOTIFICATION",
"sound" => 1,
"vibrate" => 1,
"badge" => 1,
);
$t = implode('',$tokens);
if(t != '') $message_status = send_notification($tokens, $message);
Please help me learn and resolve my issue
Just changed the field names before sending the json
change the following :
$fields = array(
'registration_ids' => $tokens,
'data' => $message
);
to
$fields = array(
'registration_ids' => $tokens,
'notification' => $message,
'priority' => 'high'
);
Related
Hello I'm trying to translate POST request api code written in php:
<?php
$methodParams = '{
"date_confirmed_from": 1407341754,
"get_unconfirmed_orders": false
}';
$apiParams = [
"method" => "getOrders",
"parameters" => $methodParams
];
$curl = curl_init("https://api.baselinker.com/connector.php");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, ["X-BLToken: xxx"]);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($apiParams));
$response = curl_exec($curl);
To Swift but I don't have idea why it doesn't work:
import UIKit
struct Parameters: Codable {
let date_confirmed_from: Int
let get_unconfirmed_orders: Bool
}
struct BodyData: Codable {
let method: String
let parameters:Parameters
}
let url = URL(string: "https://api.baselinker.com/connector.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = [
"X-BLToken": "xxx"
]
let bodyData = BodyData(method: "getOrders", parameters: Parameters(date_confirmed_from: 1407341754, get_unconfirmed_orders: false))
let encoder = JSONEncoder()
do {
let encodeData = try encoder.encode(bodyData)
request.httpBody = encodeData
let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) { (data, response, error) in
if let error = error {
print(error)
}
if let data = data {
}
}
task.resume()
}catch {
print(error)
}
When I'm testing my Swift code I'm getting error answer from API can someone help me to find fault in my code?
Does the PHP curl work?
It is not what the baseline documentation is asking for.
The documentation asks for this post data:
array (
'method' => 'getOrders',
'parameters' => '{"date_from": 1407341754}',
)
Your PHP curl request post data:
'array (
'method' => 'getOrders',
'parameters' => '{
"date_confirmed_from": 1407341754,
"get_unconfirmed_orders": false
}',
)'
The documentation asks
parameters = arguments of the requested function in JSON format.
Your parameters are an array, not JSON.
Okay I find out solution for this problem:
import UIKit
let url = URL(string: "https://api.baselinker.com/connector.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/x-www-form-urlencoded",forHTTPHeaderField: "Accept")
request.setValue("xxx",forHTTPHeaderField: "X-BLToken")
let data: Data = "method=getOrders¶meters={\"date_confirmed_from\": 1407341754&\"get_unconfirmed_orders\":false}".data(using: .utf8)!
request.httpBody = data
let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) { (data, response, error) in
if let error = error {
print(error)
}
if let data = data {
let dataString = String(data: data, encoding: .utf8)
print(dataString!)
}
}
task.resume()
The biggest problem was coding of data. curl in PHP by default sending data as x-www-form-urlencoded
I am trying to make a request to a PHP server from my swift app. For some reason php is showing an empty array as the $_REQUEST variable. I have looked through stack overflow and implemented everything I can find that might help, but still getting an empty array in php. Here is the relevant swift code...
func connect(_ pin: String, completion: #escaping(Result<ConnectResponse?, Error>) -> ()) {
let params: [String : Any] = [
"mobile_pin_connect": pin,
"device_info": UIDevice().model,
"additional_info": UIDevice().systemVersion
]
doRequest(params: params) { (data) in
if let data = data {
do {
let res = try JSONDecoder().decode(Dictionary<String, String>.self, from: data)
completion(.success(
ConnectResponse(success: (res["success"] == "true"), connect_id: res["connect_id"] ?? nil, error: res["error"] ?? nil)))
} catch {
completion(.failure(error))
}
} else {
print("in else block")
}
}
}
fileprivate func doRequest(params: [String: Any], completion: #escaping (Data?) -> ()) {
let body = createJsonBody(params)!
self.request.httpBody = body
print("Sending request with thw following variables")
print(String(data: body, encoding: .utf8)!)
print(String(data: self.request.httpBody!, encoding: .utf8))
URLSession.shared.dataTask(with: self.request) { (data, response, error) in
if let error = error {
print("Error in request: \(error)")
completion(nil)
}
let stringResult = String(data: data!, encoding: .utf8)!
let properResult = String(stringResult.map {
$0 == "." ? "=" : $0
})
let decodedData = Data(base64Encoded: properResult)
completion(decodedData)
}.resume()
}
fileprivate func createJsonBody(_ params: [String: Any]) -> Data? {
do {
let jsonData = try JSONSerialization.data(withJSONObject: params)
let body = Data(jsonData).base64EncodedData()
return body
} catch {
print("Unable to create json body: " + error.localizedDescription, error)
return nil
}
}
That sends the request to the server, the setup for the request is in the static var setup...
private static var sharedConnector: ApiConnector = {
let url = URL(string: "https://mywebsiteURLhere.com/api/mobile/challenge")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let connector = ApiConnector(request)
return connector
}()
So I have the right header values for application/json I have the request method set to post, I am base64encoding the json data and in PHP I have the setup getting php://input...
$rawRequest = file_get_contents("php://input");
and dumping the $_REQUEST variable to an error log, but I always get array\n(\n)\n
it is just showing an empty array
I even did
error_log("Raw request from index.php");
error_log(print_r($rawRequest, true));
and it logs a completely empty line.
I can't figure out why PHP is getting nothing in the request, from everything I have seen online I am doing the request correctly in swift. Any help is really appreciated. Thank you
As per your Swift Code, Can you please replace the following method.
fileprivate func createJsonBody(_ params: [String: Any]) -> Data? {
do {
let jsonData = try JSONSerialization.data(withJSONObject: params)
let body = Data(jsonData)
return body
} catch {
print("Unable to create json body: " + error.localizedDescription, error)
return nil
}
}
You need to replace this line let body = Data(jsonData) with
let body = Data(jsonData).base64EncodedData()
Without seeing your PHP code, it is difficult to determine the entire picture. However, whatever steps you perform to encode your data via the client (Swift) you must reverse to successfully decode the message on the server.
For example, if you prepare and send the request from your client as follows.
Client:
JSON encode data
base-64 encode
send data
The your server must reverse the steps to successfully decode the data.
Server:
recv data
base-64 decode data
JSON decode data
Unless your server requires it, I would remove the base-64 encode step, as it only complicates your encode / decode process.
I have created a working example: https://github.com/stuartcarnie/stackoverflow/tree/master/q59329179
Clone it or pull down the specific code in your own project.
To test, open up a terminal and run the php server:
$ cd q59329179/php
$ php -S localhost:8080 router.php
PHP 7.3.9 Development Server started at Thu Dec 19 10:47:58 2019
Listening on http://localhost:8080
Document root is /Users/stuartcarnie/projects/stackoverflow/q59329179/php
Press Ctrl-C to quit.
Test it works with curl in another terminal session:
$ curl -XPOST localhost:8080 --data-binary '{"string": "foo", "number": 5}'
Note you should see output in the php session:
[Thu Dec 19 11:33:43 2019] Array
(
[string] => foo
[number] => 5
)
Run the Swift test:
$ cd q59329179/swift
$ swift run request
Note again, decoded output in php session:
[Thu Dec 19 11:20:49 2019] Array
(
[string] => string value
[number] => 12345
[bool] =>
)
Your request is probably not arriving through the POST structure, but is kept in the request body.
Try running this as your first PHP operation:
$raw = file_get_contents('php://input');
and see what, if anything, is now into $raw. You should see a Base64 encoded string there, that you need to decode - like this, if you need an array:
$info = json_decode(base64_decode($raw), true);
I've tested your code and it's working fine. The issue might be at your PHP end. I've tested the following code on local server as well as on httpbin
The output from a local server (recent version of XAMPP (php 7.3.12)):
Sending request with thw following variables
eyJhZGRpdGlvbmFsX2luZm8iOiIxMy4yLjIiLCJtb2JpbGVfcGluX2Nvbm5lY3QiOiIxMjM0IiwiZGV2aWNlX2luZm8iOiJpUGhvbmUifQ==
result eyJhZGRpdGlvbmFsX2luZm8iOiIxMy4yLjIiLCJtb2JpbGVfcGluX2Nvbm5lY3QiOiIxMjM0IiwiZGV2aWNlX2luZm8iOiJpUGhvbmUifQ==
message ["additional_info": "13.2.2", "mobile_pin_connect": "1234", "device_info": "iPhone"]
Code:
ApiConnector.swift
import Foundation
import UIKit
class ApiConnector{
var request: URLRequest
private init(request: URLRequest) {
self.request = request
}
public static var sharedConnector: ApiConnector = {
let url = URL(string: "http://localhost/post/index.php")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let connector = ApiConnector(request: request)
return connector
}()
func connect(_ pin: String, completion: #escaping(Result<Dictionary<String, String>, Error>) -> ()) {
let params: [String : Any] = [
"mobile_pin_connect": pin,
"device_info": UIDevice().model,
"additional_info": UIDevice().systemVersion
]
doRequest(params: params) { (data) in
if let data = data {
do {
let res = try JSONDecoder().decode(Dictionary<String, String>.self, from: data)
completion(.success(res))
} catch {
completion(.failure(error))
}
} else {
print("in else block")
}
}
}
fileprivate func doRequest(params: [String: Any], completion: #escaping (Data?) -> ()) {
let body = createJsonBody(params)!
self.request.httpBody = body
print("Sending request with thw following variables")
print(String(data: body, encoding: .utf8)!)
URLSession.shared.dataTask(with: self.request) { (data, response, error) in
if let error = error {
print("Error in request: \(error)")
completion(nil)
}
let stringResult = String(data: data!, encoding: .utf8)!
print("result \(stringResult)")
let properResult = String(stringResult.map {
$0 == "." ? "=" : $0
})
let decodedData = Data(base64Encoded: properResult)
completion(decodedData)
}.resume()
}
fileprivate func createJsonBody(_ params: [String: Any]) -> Data? {
do {
let jsonData = try JSONSerialization.data(withJSONObject: params)
let body = Data(jsonData).base64EncodedData()
return body
} catch {
print("Unable to create json body: " + error.localizedDescription, error)
return nil
}
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
let session = URLSession.shared
override func viewDidLoad() {
super.viewDidLoad()
ApiConnector.sharedConnector.connect("1234") { (result) in
switch result {
case .success(let message):
print("message \(message)")
case .failure(let error):
print(error.localizedDescription)
}
}
}
}
index.php
echo file_get_contents("php://input");
You can verify your code by doing a request to https://httpbin.org/post
output:
Sending request with thw following variables
eyJkZXZpY2VfaW5mbyI6ImlQaG9uZSIsImFkZGl0aW9uYWxfaW5mbyI6IjEzLjIuMiIsIm1vYmlsZV9waW5fY29ubmVjdCI6IjEyMzQifQ==
result {
"args": {},
"data": "eyJkZXZpY2VfaW5mbyI6ImlQaG9uZSIsImFkZGl0aW9uYWxfaW5mbyI6IjEzLjIuMiIsIm1vYmlsZV9waW5fY29ubmVjdCI6IjEyMzQifQ==",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-us",
"Content-Length": "108",
"Content-Type": "application/json; charset=utf-8",
"Host": "httpbin.org",
"User-Agent": "SessionTest/1 CFNetwork/1120 Darwin/19.0.0"
},
"json": null,
"origin": "122.173.135.243, 122.173.135.243",
"url": "https://httpbin.org/post"
}
in else block
If you are running an older version of PHP then You might need HTTP_RAW_POST_DATA
Have look at this SO for more info on PHP side.
I use FCM for notification.
In firebase console i can send notification, but by PHP code not received and cant custom it
PHP code :
$data['TITLE'] = $title;
$data['TEXT'] = $text;
$fcmFields = array('to'=>$to,
'data'=>$data,
'priority'=>'high',
'time_to_live'=>$time);
$headers = array('Authorization: key='.API_ACCESS_KEY,'Content-Type: application/json');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($fcmFields));
$result = curl_exec($ch);
curl_close($ch);
return $result;
Note: by this php code i can send notification android devices
Swift Code :
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")
}
}
#available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
print(userInfo)
completionHandler([])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
print(userInfo)
completionHandler()
}
}
extension AppDelegate : MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
let dataDict:[String: String] = ["token": fcmToken]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
}
}
1- I can send notification by google console and received but not prints anything in my app log
2- I can send notification to android devices by php codes but i cant send for ios devices
3- didReceiveRemoteNotification completely not work
Can you help me ?
I add 'notification' in PHP code and fixed
$fcmFields = array('to'=>$to,
'data'=>$data,
'notification'=>array('title'=>'x','body'=>'y'),
'priority'=>'high',
'time_to_live'=>$time);
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.
I am setting up payment processing for my OSX desktop app in swift. Since there is no SDK for OSX, I am using a Web View via the PHP SDK for Braintree. I want to pass some POST data so that the price of a product is coming dynamically from my App, but it seems to not be recognized and is underfined according to PHP errors.
I know how to send POST variable to a PHP script and have done it many times, but I have a feeling something might not be right with my swift code. My PHP error is: "Notice: Undefined variable: price"
PayPal.swift
import Cocoa
import WebKit
class PayPal: NSViewController {
#IBOutlet weak var paypalWebView: WebView?
override func viewWillAppear() {
self.view.window!.title = "Payment"
}
override func viewDidLoad() {
super.viewDidLoad()
setupPP()
}
func setupPP(){
let request: NSURL = NSURL(string: "http://")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: request as URL)
urlRequest.httpMethod = "POST"
let postString = "price=45"
urlRequest.httpBody = postString.data(using: String.Encoding.utf8);
let session = URLSession.shared
let task = session.dataTask(with: urlRequest as URLRequest) {
(data, response, error) -> Void in
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
let requesting = NSURLRequest(url: request as URL)
DispatchQueue.main.async(){
self.paypalWebView?.mainFrame.load(requesting as URLRequest)
}
}
}
Braintree PHP Script
if(isset($_POST["price"])){
$price = $_POST["price"];
}
<?php $tr_data = Braintree_TransparentRedirect::transactionData(
array('redirectUrl' => "http://" ,
'transaction' => array('amount' => $price, 'type' => 'sale'))) ?>
Also the Paypal View that is essentially a web view is being activated when a user clicks on a button via a segue. I don't know if that would have anything to do with it or not?
I ended up getting it to work!
Paypal.swift
import Cocoa
import WebKit
class PayPal: NSViewController {
#IBOutlet weak var paypalWebView: WebView?
override func viewWillAppear() {
self.view.window!.title = "Payment"
}
override func viewDidLoad() {
super.viewDidLoad()
setupPP()
}
func setupPP(){
let request: NSURL = NSURL(string: "http://")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: request as URL)
urlRequest.httpMethod = "POST"
let postString = "amount=29.95"
urlRequest.httpBody = postString.data(using: String.Encoding.utf8);
let session = URLSession.shared
let task = session.dataTask(with: urlRequest as URLRequest) {
(data, response, error) -> Void in
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: .utf8)
print("responseString = \(responseString)")
}
paypalWebView?.mainFrame.load(urlRequest as URLRequest)
task.resume()
}
}
PHP Script
<?php
if (isset ($_POST['amount'])) {
$amount = $_POST['amount'];
}
$tr_data = Braintree_TransparentRedirect::transactionData(
array('redirectUrl' => "http://" . $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH),
'transaction' => array('amount' => $amount, 'type' => 'sale')))
?>