PayPal为什么不保留从请求后发送到Firebase功能的数据?

时间:2018-12-24 00:30:33

标签: android ios firebase paypal swift4.2

我已经发布了类似的问题,但是直到现在,我几乎是肯定的,这个问题与iOS和PayPal有关。

我在同一个Firebase项目上有一个同时具有Android和iOS的应用程序。 Android应用程序运行良好,但是当我尝试在iOS中将与Android代码相对应的http请求放入等效代码时,它并没有进入Pay​​Pal。

http发布请求发送到firebase函数,然后发送到PayPal,但是该函数正在接收iOS代码,但保留的时间不够长,无法到达PayPal ...参见以下内容:

Android代码

public static final MediaType MEDIA_TYPE = MediaType.parse("application/json"); ProgressDialog progress;

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();
    }
});

iOS代码:未达到PayPal

struct Payout: Codable {
    var uid: String
    var email: String
}

func payoutRequest() {

        print("payoutRequest")

        // Progress View
        self.progress.progress = value
        self.perform(#selector(updateProgressView), with: nil, afterDelay: 1.0)

        //let 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 token = "A21AAG_Cxp8qmbIuKF8Ey6vKSrff6BIyt3lS0BYkOdZV7LanUP3AJ9E4O7VczLmd8q8wrsr3rCmdUQrSh4437lfnQFnd0W65g"

        let headers: HTTPHeaders = [
            "Content-Type": "application/json",
            "Authorization": "Bearer \(token)",
            "Accept": "application/json"
        ]

        var payout = Payout(uid: uid!, email: txtPayoutEmail.text!)
        payout.uid = (FIRAuth.auth()?.currentUser?.uid)!
        payout.email = txtPayoutEmail.text!

        guard let uploadData = try? JSONEncoder().encode(payout) else { return }

        var request = URLRequest(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
        request.httpMethod = "POST"
        request.allHTTPHeaderFields = headers
        request.httpBody = uploadData as Data

        let task = URLSession.shared.uploadTask(with: request, from: uploadData) { (data, response, error) in

            if let error = error {
                print("error: \(error)")
                return
            }

            guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
                    print("server error")
                    return
            }

            let parsedObject = try! JSONSerialization.jsonObject(with: uploadData, options: .allowFragments)
            print(parsedObject)
        }

        task.resume()
    }
位于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)中,用户在文本视图中输入其PayPal电子邮件,然后选择GET PAYOUT-然后执行payoutRequest()。

从下面的日志中可以看到,它同时接收uid和电子邮件,创建了付款:

Firebase功能日志:

firebase-function logs

下一步将转到developer.paypal.com,登录信息中心并查看有关驾驶员PayPal电子邮件地址的通知,说明已收到付款。

如下图所示,Android应用程序显示此通知: paypal notification

,但是 iOS 应用的通知未显示未收到的任何内容。

而且,如果我进入对Sandbox的API调用,则表明已成功进行api调用:

http api call

然后,第二天,我在firebase-functions中收到了此消息(它说晚上8点,但直到第二天都没有得到)-基本上说收到的电子邮件为空:

firebase-function log with errors

0 个答案:

没有答案