SAWO와 Stripe를 이용한 유료 회원제 사이트 구축
23498 단어 javascriptsawostripeopensource
Stripe와 Sawo로 유료 멤버십 사이트 구축
Stripe: 인터넷 비즈니스를 위한 온라인 결제 처리. Stripe는 모든 규모의 온라인 비즈니스를 위한 상거래를 지원하는 결제 API 제품군입니다.
요구 사항
Node.js 15.5+ 이상
단계
1. SAWO API 키 생성
계속을 클릭합니다. 아래와 같은 유사한 프롬프트가 표시됩니다.
2.1 로컬 머신에서 개발하려면 호스트 이름을 'localhost'로 설정해야 합니다.
If using "localhost" as hostname is not working for you, try "127.0.0.1"
2.2 프로덕션의 경우 호스트 이름을 도메인으로 설정해야 합니다.
If you are adding your domain do not add 'https://', ''http://', 'www' or even trailing backslash. Example: https://dev.sawolabs.com/ should be kept as dev.sawolabs.com
만들기 버튼을 클릭하면 API 키 생성 프롬프트와 다운로드된 SAWO 키 csv 파일을 성공적으로 볼 수 있습니다.
2. Stripe API 키 생성 및 가격으로 제품 생성
3. 종속성 설치
터미널에 다음 명령을 입력하여 Next.js 앱을 생성합니다.
npm i stripe, express
4. index.js 파일에 끝점을 만들고 HTML 파일을 제공합니다.
const express = require("express");
const app = express();
const path = require("path");
app.use(express.static(path.join(__dirname, "public")));
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.get("/login", (req, res) => {
res.sendFile(__dirname + "/public/login.html");
});
app.get("/success", (req, res) => {
res.sendFile(__dirname + "/public/success.html");
});
app.listen("3000", console.log("Listening on port 3000."));
const stripe = require('stripe')('YOUR_STRIPE_SECRET_KEY');
const priceId = 'YOUR_PRICE_ID';
const session = await stripe.checkout.sessions.create({
billing_address_collection: 'auto',
line_items: [
{
price: prices.data[0].id,
// For metered billing, do not pass quantity
quantity: 1,
},
],
mode: 'subscription',
success_url: `${YOUR_DOMAIN}/success.html?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${YOUR_DOMAIN}/cancel.html`,
});
res.redirect(303, session.url);
});
const prices = await stripe.prices.list({
lookup_keys: [req.body.lookup_key],
expand: ['data.product'],
});
line_items: [
{
price: prices.data[0].id,
// For metered billing, do not pass quantity
quantity: 1,
},
],
success_url: `${YOUR_DOMAIN}/success.html?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${YOUR_DOMAIN}/cancel.html`,
const returnUrl = YOUR_DOMAIN;
const portalSession = await stripe.billingPortal.sessions.create({
customer: checkoutSession.customer,
return_url: returnUrl,
});
app.post(
'/webhook',
express.raw({ type: 'application/json' }),
(request, response) => {
const event = request.body;
// Replace this endpoint secret with your endpoint's unique secret
// If you are testing with the CLI, find the secret by running 'stripe listen'
// If you are using an endpoint defined with the API or dashboard, look in your webhook settings
// at https://dashboard.stripe.com/webhooks
const endpointSecret = 'whsec_12345';
// Only verify the event if you have an endpoint secret defined.
// Otherwise use the basic event deserialized with JSON.parse
if (endpointSecret) {
// Get the signature sent by Stripe
const signature = request.headers['stripe-signature'];
try {
event = stripe.webhooks.constructEvent(
request.body,
signature,
endpointSecret
);
} catch (err) {
console.log(`⚠️ Webhook signature verification failed.`, err.message);
return response.sendStatus(400);
}
}
let subscription;
let status;
// Handle the event
switch (event.type) {
case 'customer.subscription.trial_will_end':
subscription = event.data.object;
status = subscription.status;
console.log(`Subscription status is ${status}.`);
// Then define and call a method to handle the subscription trial ending.
// handleSubscriptionTrialEnding(subscription);
break;
case 'customer.subscription.deleted':
subscription = event.data.object;
status = subscription.status;
console.log(`Subscription status is ${status}.`);
// Then define and call a method to handle the subscription deleted.
// handleSubscriptionDeleted(subscriptionDeleted);
break;
case 'customer.subscription.created':
subscription = event.data.object;
status = subscription.status;
console.log(`Subscription status is ${status}.`);
// Then define and call a method to handle the subscription created.
// handleSubscriptionCreated(subscription);
break;
case 'customer.subscription.updated':
subscription = event.data.object;
status = subscription.status;
console.log(`Subscription status is ${status}.`);
// Then define and call a method to handle the subscription update.
// handleSubscriptionUpdated(subscription);
break;
default:
// Unexpected event type
console.log(`Unhandled event type ${event.type}.`);
}
// Return a 200 response to acknowledge receipt of the event
response.send();
}
);
결론
축하합니다! 끝까지 하셨고 SAWO에서 인증을 구현하는 방법과 유료 멤버십을 위한 Stripe API를 통합하는 방법을 배웠습니다. 어려움에 직면한 경우 방금 살펴본 자습서working demo를 참조하십시오. 동일한 소스 코드here를 찾으십시오.
무엇 향후 계획?
이제 Stripe 및 Sawo를 사용하여 유료 멤버십 사이트를 구축하는 방법을 배웠으므로 자유롭게 SAWO documentation을 살펴보고 저장소에서 포크하여 이 데모 애플리케이션에 몇 가지 새로운 기능을 통합하십시오.
Reference
이 문제에 관하여(SAWO와 Stripe를 이용한 유료 회원제 사이트 구축), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://dev.to/karankartikeya/build-a-paid-membership-site-using-sawo-and-stripe-2gda
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
이제 Stripe 및 Sawo를 사용하여 유료 멤버십 사이트를 구축하는 방법을 배웠으므로 자유롭게 SAWO documentation을 살펴보고 저장소에서 포크하여 이 데모 애플리케이션에 몇 가지 새로운 기능을 통합하십시오.
Reference
이 문제에 관하여(SAWO와 Stripe를 이용한 유료 회원제 사이트 구축), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/karankartikeya/build-a-paid-membership-site-using-sawo-and-stripe-2gda텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)