android - 使用 iOS Swift 发送 post html 请求不起作用
问题描述
我已经通过 PayPal 使用 Android 和 IOS 为我的应用程序设置了支付系统。
只需单击一个按钮,就会调用“payoutRequest”方法,并通过 Firebase 函数将必要的信息发送到 PayPal。
我的代码在 Android 上运行得很好,但在 iOS 上就不行了。
安卓的方法:payoutRequest
public static final MediaType MEDIA_TYPE = MediaType.parse("application/json");
ProgressDialog progress;
private void payoutRequest() {
progress = new ProgressDialog(this);
progress.setTitle("Processing your payout ...");
progress.setMessage("Please Wait .....");
progress.setCancelable(false);
progress.show();
// HTTP Request ....
final OkHttpClient client = new OkHttpClient();
// in json - we need variables for the hardcoded uid and Email
JSONObject postData = new JSONObject();
try {
postData.put("uid", FirebaseAuth.getInstance().getCurrentUser().getUid());
postData.put("email", mPayoutEmail.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
// Request body ...
RequestBody body = RequestBody.create(MEDIA_TYPE, postData.toString());
// Build Request ...
final Request request = new Request.Builder()
.url("https://us-central1-myapp.cloudfunctions.net/payout")
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("cache-control", "no-cache")
.addHeader("Authorization", "Your Token")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// something went wrong right off the bat
progress.dismiss();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// response successful ....
// refers to response.status('200') or ('500')
int responseCode = response.code();
if (response.isSuccessful()) {
switch(responseCode) {
case 200:
Snackbar.make(findViewById(R.id.layout),
"Payout Successful!", Snackbar.LENGTH_LONG)
.show();
break;
case 500:
Snackbar.make(findViewById(R.id.layout),
"Error: no payout available", Snackbar
.LENGTH_LONG).show();
break;
default:
Snackbar.make(findViewById(R.id.layout),
"Error: couldn't complete the transaction",
Snackbar.LENGTH_LONG).show();
break;
}
} else {
Snackbar.make(findViewById(R.id.layout),
"Error: couldn't complete the transaction",
Snackbar.LENGTH_LONG).show();
}
progress.dismiss();
}
});
}
上述方法通过创建的 Firebase 函数向 PayPal 发送 html 请求,见下图(firebase 函数):
index.js
- 与 Firebase 函数一起使用的 JavaScript 文件**
'use strict';
const functions = require('firebase-functions');
const paypal = require('paypal-rest-sdk');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
paypal.configure({
mode: 'sandbox',
client_id: functions.config().paypal.client_id,
client_secret: functions.config().paypal.client_secret
})
exports.newRequest = functions.database.ref('/history/{pushId}').onCreate((snapshot, context) => {
var requestSnapshot = snapshot.val();
var price = snapshot.child('ridePrice').val();
var pushId = context.params.pushId;
return snapshot.ref.parent.child(pushId).child('price').set(price);
});
function getPayoutsPending(uid) {
return admin.database().ref('Users/Drivers/' + uid + '/history').once('value').then((snap) => {
if(snap === null){
throw new Error("profile doesn't exist");
}
var array = [];
if(snap.hasChildren()){
snap.forEach(element => {
if (element.val() === true) {
array.push(element.key);
}
});
}
return array;
}).catch((error) => {
return console.error(error);
});
}
function getPayoutsAmount(array) {
return admin.database().ref('history').once('value').then((snap) => {
var value = 0.0;
if(snap.hasChildren()){
snap.forEach(element => {
if(array.indexOf(element.key) > -1) {
if(element.child('price').val() !== null){
value += element.child('price').val();
}
}
});
return value;
}
return value;
}).catch((error) => {
return console.error(error);
});
}
function updatePaymentsPending(uid, paymentId) {
return admin.database().ref('Users/Drivers/' + uid + '/history').once('value').then((snap) => {
if(snap === null){
throw new Error("profile doesn't exist");
}
if(snap.hasChildren()){
snap.forEach(element => {
if(element.val() === true) {
admin.database().ref('Users/Drivers/' + uid + '/history/' + element.key).set( {
timestamp: admin.database.ServerValue.TIMESTAMP,
paymentId: paymentId
});
admin.database().ref('history/' + element.key + '/driverPaidOut').set(true);
}
});
}
return null;
}).catch((error) => {
return console.error(error);
});
}
exports.payout = functions.https.onRequest((request, response) => {
return getPayoutsPending(request.body.uid)
.then(array => getPayoutsAmount(array))
.then(value => {
var valueTrunc = parseFloat(Math.round((value * 0.75) * 100) / 100).toFixed(2);
const sender_batch_id = Math.random().toString(36).substring(9);
const sync_mode = 'false';
const payReq = JSON.stringify({
sender_batch_header: {
sender_batch_id: sender_batch_id,
email_subject: "You have a payment"
},
items: [
{
recipient_type: "EMAIL",
amount: {
value: valueTrunc,
currency: "CAD"
},
receiver: request.body.email,
note: "Thank you.",
sender_item_id: "Ryyde Payment"
}
]
});
return paypal.payout.create(payReq, sync_mode, (error, payout) => {
if (error) {
console.warn(error.response);
response.status('500').end();
throw error;
}
console.info("payout created");
console.info(payout);
return updatePaymentsPending(request.body.uid, sender_batch_id)
});
}).then(() => {
response.status('200').end();
return null;
}).catch(error => {
console.error(error);
});
});
当我在 Android 中运行上面的代码时,它可以正常工作,但下面的方法不适用于 IOS(两个平台使用相同的 index.js 文件)。
iOS的方法payoutRequest
::
func payoutRequest() {
print("payoutRequest")
// Progress View
self.progress.progress = value
self.perform(#selector(updateProgressView), with: nil, afterDelay: 1.0)
let email = txtPayoutEmail.text!
let url = "https://us-central1-myapp.cloudfunctions.net/payout"
let params : Parameters = [
"uid": self.uid! as String,
"email": email
]
let headers : HTTPHeaders = [
"Content-Type": "application/json",
"Authorization": "Your Token",
"cache-control": "no-cache"
]
let myData = try? JSONSerialization.data(withJSONObject: params, options: [])
print("data: \(String(describing: myData))")
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers)
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseData(completionHandler: { (response) in
//print("Request: \(String(describing: response.request))") // original url request
//print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
switch response.result {
case .success:
print("Validation Successful")
let parsedObject = try! JSONSerialization.jsonObject(with: myData!, options: .allowFragments)
print("parsed: \(parsedObject)")
case .failure(let error):
print(error)
}
})
}
此外,出于隐私问题,以下网址并不完全准确。 https://us-central1-myapp.cloudfunctions.net/payout (myapp) 不是应用程序的名称
我已将问题缩小到 iOS 中的实际方法 -payoutRequest
没有按应有的方式发送 post html 请求。
我可能做错了什么?
编辑
运行下面的代码(payoutRequest())后是 print() 语句: ** app name is blacked **
此外,如果我转到我的 PayPal 开发者帐户,进入仪表板并单击通知,我应该会收到以下通知:
- 主账户中收到的付款(ok)
- 从骑手电子邮件帐户收到的付款(好的)
- 支付给司机的款项(无)
- 大量支付给司机(无)
解决方案
推荐阅读
- sql - SQL中的动态减法
- java - 使用 jpa findall java 从表中仅获取一些属性
- c++ - NtCreateUserProcess 之后的 NtResumeThread
- php - Laravel 相当于 sql 日期时间转换
- javascript - 在Vuejs中离开页面时如何在url路径中保存页码
- shell - SingleColumnValueFilter 未正确过滤表
- terraform - Terraform 模块之间的可共享“计数”元参数?
- python - AttributeError:模块'keras.utils'没有使用segmentation_models的属性'get_file'
- hibernate - 使用 JPA 连接来自不同表的列
- python - 使用 Spark 创建“EventID”列以帮助区分不同的记录集