我在同一Firebase项目的Android和iOS上都有一个应用程序。该应用程序的最后一部分是将数据从我的应用程序发送到firebase-function,然后再发送到PayPal。它可以在Android中使用,但不能在iOS中使用。请参见下面的代码。
我什至与PayPal交谈过,但他们认为这是iOS代码。我在GitHub,PayPal,Stack Overflow等网站上发布了帖子,看不到任何解决方法。
基本上,当我按下一个按钮-GET PAYOUT时,将执行payoutRequest()方法。它应将“ uid”和“ email”发送到该功能,然后发送到PayPal。
该功能中包含PayPal SDK。
它不会将数据发送到PayPal,但是会在功能中被识别(https功能不是可调用功能)
Android代码正常工作
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-ryyde-sj.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功能:index.js
'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('price').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: "Payment"
}
]
});
return paypal.payout.create(payReq, sync_mode, (error, payout) => {
if (error) {
console.warn(error.response);
response.status('500').end();
throw error;
}
console.info("uid: " + request.body.uid + " email: " + request.body.email) // testing
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);
});
});
IOS代码:payoutRequest()
var params: Parameters = ["uid": FIRAuth.auth()?.currentUser!.uid as Any, "email": txtPayoutEmail.text!]
let url = URL(string: "https://us-central1-ryyde-sj.cloudfunctions.net/payout")
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"Authorization": "Your Token",
"cache-control": "no-cache"
]
let request = NSMutableURLRequest(url: url!)
let session = URLSession.shared
request.httpMethod = "POST"
params = params as! Dictionary<String, String>
request.httpBody = try! JSONSerialization.data(withJSONObject: params, options: [])
request.allHTTPHeaderFields = headers
let task = session.dataTask(with: request as URLRequest) { data, response, error in
guard data != nil, error == nil else {
print("no data found: \(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("status code: \(httpStatus.statusCode)")
print("response: \(String(describing: response))")
}
let jsonData = try? JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
let parsedObject = try! JSONSerialization.jsonObject(with: jsonData!, options: .allowFragments)
print(parsedObject)
}
task.resume()
会发生什么
执行方法(payoutRequest())时,Firebase函数中的日志显示保留了'uid'和'email'参数:
如您在控制台的第三行所看到的,uid和email参数被保留。
接下来要发生的事情是,应该将数据(参数)发送到Paypal,并将通知发送到电子邮件地址,说明已收到付款,例如:
,但没有此类通知。
如果我检查对Sandbox的API调用,则会看到以下内容:
然后,每天4个小时后,我在日志中收到此错误,基本上,由于PayPal不保留发送的数据,该错误又重新出现了:
答案 0 :(得分:0)
您在iOS代码上遇到的问题之一是params
的值应为[String: String]
类型(这是POST数据的必需类型)。
我指的是这一行:
var参数:参数= [“ uid”:FIRAuth.auth()?. currentUser!.uid为Any,“ email”:txtPayoutEmail.text!]
尝试将uid强制转换为String:
var参数:参数= [“ uid”:FIRAuth.auth()?. currentUser!.uid作为字符串,“ email”:txtPayoutEmail.text!]