我已经使用Android和IOS通过PayPal为我的应用程序设置了付款系统。
单击按钮,将调用方法“ payoutRequest”,并将必要的信息通过Firebase Functions发送到PayPal。
我拥有的代码在Android上可以完美运行,但在iOS上则无法正常工作。
Android的方法: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函数将html请求发送到PayPal,请参见下文(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
没有发送应有的html请求。
我可能做错了什么?
编辑
运行下面的代码(payoutRequest())之后是print()语句: **应用名称被涂黑**
此外,如果我转到我的PayPal开发人员帐户,请进入仪表板,然后单击“通知”,我将收到以下通知: