firestore,firebase云功能,android
我想在我的android应用程序中使用Paypal进行付款,该付款方法允许付款购买一些硬币来玩游戏。因此我找到了一些教程,但不幸的是它不完整或不清楚,并且看到了Firebase云文档。测试中,我将这些步骤集成起来:
1-paypal按钮进入了Android应用,我做到了。
2使用Firebase云作为服务器端:我做了一些代码 现在我备货充足,不知道下一步该怎么做
我应该在我的云函数,firestore和android活动中做什么? 这是我对paypalfragment的实现
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_payment,container, false);
////===================recyclerview===================================
RecyclerView PaymentRV=view.findViewById(R.id.Payment_RV);
PaymentRV.setLayoutManager(new
LinearLayoutManager(container.getContext()));
PaymentRV.setHasFixedSize(true);
//========================firebase=========================
firestore=FirebaseFirestore.getInstance();
//=========================================================
//Inside onCreate() method we need to start PayPalService.
Intent intent=new Intent(getActivity(),PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION,config);
getActivity().startService(intent);
//PaymentDatabase=FirebaseFirestore.getInstance();
Query query=firestore.collection("Payments");
FirestoreRecyclerOptions<PaymentItem> options=new FirestoreRecyclerOptions.Builder<PaymentItem>()
.setQuery(query,PaymentItem.class)
.build();
PaymentAdapter=new FirestoreRecyclerAdapter<PaymentItem, PaymentViewHolder>(options) {
@Override
protected void onBindViewHolder(@NonNull PaymentViewHolder holder, int position, @NonNull PaymentItem model) {
holder.setItem(model.getItem());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
paypalPayment();
}
});
}
@NonNull
@Override
public PaymentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.payment_item,parent,false);
return new PaymentViewHolder(view);
}
};
PaymentRV.setAdapter(PaymentAdapter);
//===========================payment button================================
return view;
}//=========tell app if is ready to publish or not
//============production ready to publish
//Now to get Payment from PayPal we need a PayPal Configuration Object and a Request Code.
private int PAYPAL_REQUEST_CODE = 1;
//Paypal Configuration Object
private static PayPalConfiguration config=new PayPalConfiguration()
// Start with mock environment. When ready, switch to sandbox (ENVIRONMENT_SANDBOX)
// or live (ENVIRONMENT_PRODUCTION)
.environment(PayPalConfiguration.ENVIRONMENT_SANDBOX)
.clientId(paypalConfig.PAYPAL_CLIENT_ID);
//Inside onCreate() method we need to start PayPalService.
private void paypalPayment() {
//Creating a paypalpayment
PayPalPayment payment=new PayPalPayment(new BigDecimal(.1),"USD","Coins",
PayPalPayment.PAYMENT_INTENT_SALE);
//crate paypal payment activity intent
Intent i=new Intent(getActivity(),PaymentActivity.class);
i.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION,config);
i.putExtra(PaymentActivity.EXTRA_PAYMENT,payment);
startActivityForResult(i,PAYPAL_REQUEST_CODE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//If the result is from paypal
if(requestCode==PAYPAL_REQUEST_CODE){
//If the result is OK i.e. user has not canceled the payment
if(resultCode== Activity.RESULT_OK){
PaymentConfirmation confirm=data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
//if confirmation is not null
if(confirm!=null){
try {
//getting the payment details
//Getting the payment details
{
JSONObject jsonObj = new JSONObject(confirm.toJSONObject().toString());
String paymentResponse = jsonObj.getJSONObject("response").getString("state");
if(paymentResponse.equals("approved")){
Toast.makeText(getContext(),"Payment successful",Toast.LENGTH_LONG).show();
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
assert currentUser != null;
String uid = currentUser.getUid();
HashMap<String,Boolean> m=new HashMap<>();
m.put("customerPaid",true);
firestore.collection("Users")
.document(uid)
.set(m, SetOptions.merge());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}else{
Toast.makeText(getContext(),"payment unsuccessful",Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onDestroy() {
getActivity().stopService(new Intent(getActivity(),PayPalService.class));
super.onDestroy();
}
public class PaymentViewHolder extends RecyclerView.ViewHolder {
private View view;
public PaymentViewHolder(View itemView) {
super(itemView);
view=itemView;
}
public void setItem(String item) {
TextView Item=view.findViewById(R.id.item);
Item.setText(item);
}
}
@Override
public void onStart() {
super.onStart();
PaymentAdapter.startListening();
}
@Override
public void onStop() {
super.onStop();
if (PaymentAdapter != null) {
PaymentAdapter.stopListening();
}
}
这是我的文档功能
'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.payout=functions.https.onRequest((req,res)=>{
const sender_batch_id = Math.random().toString(36).substring(9);
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: 0.90,
currency: "USD"
},
receiver: "amrmahmoudPP@app.com",
note: "Thank you.",
sender_item_id: "item_3"
}
]
});
paypal.payout.create(payReq,(error, payout)=>{
if (error) {
console.warn(error.res);
res.status('500').end();
throw error;
}else{
console.info("payout created");
console.info(payout);
res.status('200').end();
}
});
});
exports.process = functions.https.onRequest((req, res) => {
const paymentId = req.query.paymentId;
const payerId = {
payer_id: req.query.PayerID
};
return paypal.payout.execute(paymentId, payerId, (error, payout) => {
if (error) {
console.error(error);
} else {
if (payout.state === 'approved') {
console.info('payment completed successfully, description: ', payout.transactions[0].description);
// console.info('req.custom: : ', payment.transactions[0].custom);
// set paid status to True in RealTime Database
// const date = Date.now();
// const uid = payout.transactions[0].description;
// const ref=admin.firestore().collection("Users").doc(uid);
// const ref = admin.database().ref('users/' + uid + '/');
// ref.push({
// 'paid': true,
// // 'description': description,
// 'date': date
// })
} else {
console.warn('payment.state: not approved ?');
}
}
}).then(r =>
console.info('promise: ', r));
}); firebase.json
{
"hosting": {
"public": "public",
"ignore": ["firebase.json","**/.*","**/node_modules/**"],
"rewrite":[{"source":"/payout","function":"payout"}]
},
"functions": {
"predeploy": [
"npm --prefix \"$RESOURCE_DIR\" run lint"
]
}
}