[英]Format array for Stripe multiple plan subscription api call
我正在嘗試向Stripe API發送多個計划訂閱請求。 但是我有這樣的數組
0: {"plan":"plan_EaDE7UnYYcicOj","quantity":"2"}
1: {"plan":"plan_EbOzfXj7R9hcdz","quantity":"2"}
我想將其轉換為Stripe想要的格式,如下所示
curl https://api.stripe.com/v1/subscriptions \
-u sk_test_XXXXXXXXXXXXXXXXXX: \
-d customer=cus_4fdAW5ftNQow1a \
-d items[0][plan]=plan_CBXbz9i7AIOTzr \
-d items[0][quantity]=2
-d items[1][plan]=plan_IFuCu48Snc02bc \
-d items[1][quantity]=2
我正在使用如下的獲取方法
const response = await fetch("https://api.stripe.com/v1/subscriptions", {
method: 'post',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer " + apiKey
},
body: encodeBody(customerId, items) //problem here
});
我一直在嘗試將數組編碼為正確的格式,但是每次我得到[Object Object]時,由於encode.concat,客戶ID便合並在一起
function encodeBody(customerId, items){
let encoded = "";
for (let [k, v] of Object.entries(items)) {
encoded = encoded.concat(k,"=", encodeURI(v), "&");
}
encoded = encoded.concat("customer", encodeURI(customerId));
return encoded;
}
我是使用編碼功能的新手,所以我不知道該怎么做。
您希望查詢字符串的items
采用以下格式:
items[0][plan]=plan_CBXbz9i7AIOTzr&items[1][plan]=plan_IFuCu48Snc02bc&items[1][quantity]=2
為此,您要遍歷plans
和每個plan
上的屬性。 您可以通過實現encodeBody()
來實現此encodeBody()
使用ES6,因為我看到您已經在上面使用const
):
function encodeBody(customerId, items) {
let encoded = '';
for (let i = 0; i < items.length; i++) {
const item = items[i];
for (pair of Object.entries(item)) {
console.log(pair);
encoded += `items[${i}][${pair[0]}]=${pair[1]}&`;
}
}
encoded += `customer=${customerId}`;
return encoded;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.