[英]Format array for Stripe multiple plan subscription api call
I'm trying to send multiple plan subscription request to the Stripe API. 我正在尝试向Stripe API发送多个计划订阅请求。 However I have an array like this
但是我有这样的数组
0: {"plan":"plan_EaDE7UnYYcicOj","quantity":"2"}
1: {"plan":"plan_EbOzfXj7R9hcdz","quantity":"2"}
I want to convert it so that it is in the format that Stripe wants it which is like this 我想将其转换为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
I'm using the fetch method like below 我正在使用如下的获取方法
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
});
I have been trying to encode the array into a proper format but everytime I get [Object Object] and the customer id is joined together due to encode.concat 我一直在尝试将数组编码为正确的格式,但是每次我得到[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;
}
I'm new to using the encoding function so I don't understand what to do. 我是使用编码功能的新手,所以我不知道该怎么做。
You want your query string's items
to be in this format: 您希望查询字符串的
items
采用以下格式:
items[0][plan]=plan_CBXbz9i7AIOTzr&items[1][plan]=plan_IFuCu48Snc02bc&items[1][quantity]=2
To do that, you want to iterate over both the plans
and the properties on each plan
. 为此,您要遍历
plans
和每个plan
上的属性。 You can achieve this with this implementation of encodeBody()
(uses ES6 since I see you're already using const
above): 您可以通过实现
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.