【问题标题】:Cloud Functions as API作为 API 的云函数
【发布时间】:2018-08-06 18:21:48
【问题描述】:

我想使用 HTTP Cloud 函数作为 API。我使用 Retrofit 作为 REST 客户端并发送 POST 请求(我使用 HTTP Cloud 函数 URL 作为 API 端点)。函数读取作为 POST 参数发送的参数并处理它们,我想要将函数中的某些内容作为响应传递给客户端。我该怎么做? 这是我的云函数代码:

exports.Add = functions.https.onRequest((req,res)=>{
//var testPublicKey = sk_test_N63fpbFHY2pN7XAllv9D5qjw
var stripe = require("stripe")("stripe_key");

console.log("Token:"+req.body.Token)
console.log("Amount:"+req.body.Amount)

var tokenToCharge = req.body.Token;
const amountToCharge = req.body.Amount;
var authID = req.body.AuthID;
const databaseRef = admin.firestore();
const payer = databaseRef.collection('deyaPayUsers').doc(authID).collection('Wallet').doc(authID);
 const balance = payer.Usd
 stripe.charges.create({
amount : amountToCharge,
currency : "usd",
description : "charge created",
source : tokenToCharge,
}, function(err, charge) {
if(charge.status === "succeeded"){
var trans = databaseRef.runTransaction(t=>{
 return t.get(payer)
    .then(doc=>{
     var updatedBalance = doc.data().Usd + parseInt(charge.amount);
     t.update(payer,{Usd : updatedBalance});
    });//return close
 }).then(result=>{
 console.log('Transaction success!');
 }).catch(err=>{
 console.log('Transaction Failure:',err);
 });
 }
});
});

这是我的 REST 客户端

Retrofit.Builder builder = new Retrofit.Builder()
                               .baseUrl(" https://us-central1-deyapay-
                               192704.cloudfunctions.net/tokenAmt/")
                    .addConverterFactory(GsonConverterFactory.create());
                        Retrofit retrofit = builder.build();
                        executeForm(token1,a,UID);
   private void executeForm(String Token,Integer Amt,String UID){
        Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl(" https://us-central1-deyapay-192704.cloudfunctions.net/Add/")
                .addConverterFactory(GsonConverterFactory.create());
        Retrofit retrofit =  builder.build();

        APIService apiservice=retrofit.create(APIService.class);
        Call<PostData> call=apiservice.savePost(Token,Amt,UID);
        call.enqueue(new Callback<PostData>() {
            @Override
            public void onResponse(Call<PostData> call, Response<PostData> response) {
                if(response.isSuccessful()){
                    Toast.makeText(Stripe.this, (CharSequence) response.body(),Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<PostData> call, Throwable t) {
             Toast.makeText(Stripe.this,"Failure",Toast.LENGTH_SHORT).show();

            }
        });
    } 

我的 POJO 课程

public class PostData {

    @SerializedName("Token")
    @Expose
    private String token;
    @SerializedName("Amount")
    @Expose
    private Integer amount;
    @SerializedName("AuthID")
    @Expose
    private String authID;

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public Integer getAmount() {
        return amount;
    }

    public void setAmount(Integer amt) {
        this.amount = amt;
    }

    public String getAuthID(){return authID;}

    public void setAuthID(String authID){
        this.authID = authID;
    }

}

【问题讨论】:

  • 显示APIService类代码

标签: android retrofit2 google-cloud-functions


【解决方案1】:

与 Express.js 类似,响应有 .status().send()

只需在您的console.log('Transaction success!') 附近添加res.status(200).send('stringified JSON') 您可以省略状态,但拥有它是个好主意。甚至可以在您的应用程序失败时发送其他状态码?

【讨论】:

  • 客户端如何接收
  • 假设您的代码有效,它将在您的回调 onResponse 中成为您的 response.body() 的一部分
  • 我想从我的后端返回一个字符串,所以我想检索 response.body() 作为一个字符串但是当我尝试它时, response.body() 的类型必须是 PoatData 这是我的 POJO 类的名称。
  • 我无法帮助您解决问题的 android/java 部分。
  • 什么是字符串化 JSON
猜你喜欢
  • 2020-08-15
  • 1970-01-01
  • 2017-10-13
  • 1970-01-01
  • 2022-11-30
  • 2020-05-02
  • 1970-01-01
  • 2022-11-29
相关资源
最近更新 更多