initial commit

This commit is contained in:
equippedcoding-master
2025-09-17 09:37:06 -05:00
parent 86108ca47e
commit e2c98790b2
55389 changed files with 6206730 additions and 0 deletions
@@ -0,0 +1,25 @@
# Subscriptions with fixed price
An [Express server](http://expressjs.com) implementation.
## Requirements
- Node v10+
- [Configured .env file](../../../README.md#env-config)
## How to run
1. Install dependencies
```
npm install
```
2. Run the application
```
npm start
```
3. Go to `localhost:4242` to see the demo
@@ -0,0 +1,88 @@
import {decode,encode} from 'html-entities';
function executeMysqlConnection(query){
let con = createMySQLConnection();
con.connect(function(err) {
if (err) throw err;
con.query(`SELECT * FROM subdomain_properties WHERE SubDomain = '${subdomain}'`, function (err, results) {
if (err) throw err;
// con.end();
if(results.length > 0){
}else{
}
});
});
}
function update(connection){
}
/**
*
* Update json_data
*
* @param {object} json_data
* @param {string} db_table
* @param {object} connection
* @param {function} cb
*/
export function updateJsonData(json_data,db_table,connection,cb){
let data = encode(JSON.stringify(json_data));
const sql = `UPDATE ${db_table} SET jsontext = "${data}" WHERE mysql_id = "${json_data.json.mysql_id}"`;
connection.connect(function(err) {
if (err) throw err;
con.query(sql, function (err, results) {
if (err) throw err;
con.end();
if(cb!=undefined) cb();
});
});
}
export function updateMySQLMemberUsersJSONData(connection,email,json_data){
// const sql = 'UPDATE `users` SET `age` = 20 WHERE `name` = "Josh" LIMIT 1';
const sql = `UPDATE member_users SET json_data = "${json_data}" WHERE email = "${email}"`;
connection.connect(function(err) {
if (err) throw err;
con.query(sql, function (err, results) {
if (err) throw err;
con.end();
});
});
}
export async function getMemberUser(connection,email,callback){
connection.connect(function(err) {
if (err) throw err;
connection.query(`SELECT * FROM member_users WHERE email = '${email}'`, function (err, results) {
if (err) throw err;
con.end();
if(results.length > 0){
let membersuser = {
username: results[i].username,
json_data: results[i].json_data
};
callback(results[i]);
}else{
callback(false);
}
});
});
}
@@ -0,0 +1,24 @@
{
"name": "appfactorystudio_stripe_subscriptions",
"version": "1.0.0",
"description": "Stripe subscriptions.",
"main": "server.js",
"type": "module",
"scripts": {
"start": "node server.js"
},
"author": "appfactorystudio",
"dependencies": {
"autoprefixer": "^10.4.0",
"body-parser": "^1.19.0",
"cookie-parser": "^1.4.5",
"dotenv": "^16.0.0",
"express": "^4.17.1",
"stripe": "14.3.0",
"ejs": "^3.1.6",
"html-entities": "^2.4.0",
"mysql2": "^3.6.0",
"node-fetch": "^3.2.1"
}
}
+111
View File
@@ -0,0 +1,111 @@
<?php
$param1 = $argv[1];
function _sendEmail($param2,$param3 ){
$config_domain = __get_main_configurations();
$managed_domain = $config_domain["managed_domain"];
$config = $config_domain["configurations"];
// echo json_encode($config);
// echo json_encode($GLOBALS) . "\n";
// echo $_ENV['MY_HOST'] . "\n";
$integration = GetActiveEmailIntegration($config);
if($integration==null){
EchoJsonResponse("Email integration is null!");
return;
}
$otherdata = json_decode(file_get_contents($param3), true);
$otherdata["mail_handlers"]["email_response"]["integration"] = $integration;
$otherdata["mail_handlers"]["email_confirm"]["integration"] = $integration;
$otherdata["mail_handlers"]["email_alert"]["integration"] = $integration;
Utils_WriteFile("/mnt/appfactorystudio/tmp/tmpfile1.json",$otherdata);
SendEmailBuilder($otherdata["mail_handlers"]["email_response"],$managed_domain, function($resp1) use($otherdata,$managed_domain) {
Utils_WriteFile("/mnt/appfactorystudio/tmp/tmpfile2.json",$resp1);
SendEmailBuilder($otherdata["mail_handlers"]["email_confirm"],$managed_domain, function($resp2) use($otherdata,$managed_domain,$resp1){
Utils_WriteFile("/mnt/appfactorystudio/tmp/tmpfile2.json",$resp2);
SendEmailBuilder($otherdata["mail_handlers"]["email_alert"],$managed_domain, function($resp3) use($otherdata,$managed_domain,$resp1,$resp2){
// EchoJsonObject(["resp1" => $resp1, "resp2" => $resp2]);
Utils_WriteFile("/mnt/appfactorystudio/tmp/tmpfile3.json",$resp3);
});
});
});
// $db = new DB();
// $rows = $db->query("SELECT * FROM general_data_storage WHERE name='$param2'",[],PDO::FETCH_ASSOC);
// if($rows->count() > 0){
// $mydata = $rows->results()[0];
// $mydata["json"] = html_entity_decode($mydata["json"]);
// $otherdata = json_decode($mydata["json"], true);
// $otherdata["mail_handlers"]["email_response"]["integration"] = $integration;
// $otherdata["mail_handlers"]["email_confirm"]["integration"] = $integration;
// // EchoJsonObject(["data" => json_last_error(), "param" => $param2, "count" => $rows->count()]);
// SendEmailBuilder($otherdata["mail_handlers"]["email_response"],$managed_domain, function($resp1) use($otherdata,$managed_domain) {
// SendEmailBuilder($otherdata["mail_handlers"]["email_confirm"],$managed_domain, function($resp2) use($otherdata,$managed_domain,$resp1){
// EchoJsonObject(["mail_handlers" => $otherdata, "resp1" => $resp1, "resp2" => $resp2]);
// });
// });
// // EchoJsonResponse("Sending...");
// }else{
// EchoJsonResponse("No record found");
// }
// $db = null;
}
function _sendEmail2($param2,$param3 ){
$config_domain = __get_main_configurations();
$managed_domain = $config_domain["managed_domain"];
$config = $config_domain["configurations"];
$integration = GetActiveEmailIntegration($config);
if($integration==null){
EchoJsonResponse("Email integration is null!");
return;
}
$otherdata = json_decode(file_get_contents($param3), true);
foreach ($otherdata["mail_handlers"] as $key => $value) {
// $value[$key]["integration"] = $integration;
$otherdata["mail_handlers"][$key]["integration"] = $integration;
$mail = $otherdata["mail_handlers"][$key];
SendEmailBuilder($mail,$managed_domain, function($resp) use($otherdata,$managed_domain,$key){
EchoJsonObject(["resp1" => $resp["emails"]]);
});
}
}
if($param1=="send_email"){
require dirname( __DIR__,4 ) . "/core/api/php/includes/init.php";
require dirname( __DIR__,4 ) . "/core/api/php/includes/functions.php";
$param2 = $argv[2];
$param3 = $argv[3];
_sendEmail($param2,$param3);
}
if($param1=="send_email2"){
require dirname( __DIR__,4 ) . "/core/api/php/includes/init.php";
require dirname( __DIR__,4 ) . "/core/api/php/includes/functions.php";
$param2 = $argv[2];
$param3 = $argv[3];
_sendEmail2($param2,$param3);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,269 @@
const express = require('express');
const app = express();
const { resolve } = require('path');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
// Replace if using a different env file or config
require('dotenv').config({ path: './.env' });
if (
!process.env.STRIPE_SECRET_KEY ||
!process.env.STRIPE_PUBLISHABLE_KEY ||
!process.env.STATIC_DIR
) {
console.log(
'The .env file is not configured. Follow the instructions in the readme to configure the .env file. https://github.com/stripe-samples/subscription-use-cases'
);
console.log('');
process.env.STRIPE_SECRET_KEY
? ''
: console.log('Add STRIPE_SECRET_KEY to your .env file.');
process.env.STRIPE_PUBLISHABLE_KEY
? ''
: console.log('Add STRIPE_PUBLISHABLE_KEY to your .env file.');
process.env.STATIC_DIR
? ''
: console.log(
'Add STATIC_DIR to your .env file. Check .env.example in the root folder for an example'
);
process.exit();
}
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY, {
apiVersion: '2022-08-01',
appInfo: { // For sample support and debugging, not required for production:
name: "stripe-samples/subscription-use-cases/fixed-price",
version: "0.0.1",
url: "https://github.com/stripe-samples/subscription-use-cases/fixed-price"
}
});
// Use static to serve static assets.
app.use(express.static(process.env.STATIC_DIR));
// Use cookies to simulate logged in user.
app.use(cookieParser());
// Use JSON parser for parsing payloads as JSON on all non-webhook routes.
app.use((req, res, next) => {
if (req.originalUrl === '/webhook') {
next();
} else {
bodyParser.json()(req, res, next);
}
});
app.get('/', (req, res) => {
const path = resolve(process.env.STATIC_DIR + '/register.html');
res.sendFile(path);
});
app.get('/config', async (req, res) => {
const prices = await stripe.prices.list({
lookup_keys: ['sample_basic', 'sample_premium'],
expand: ['data.product']
});
res.send({
publishableKey: process.env.STRIPE_PUBLISHABLE_KEY,
prices: prices.data,
});
});
app.post('/create-customer', async (req, res) => {
// Create a new customer object
const customer = await stripe.customers.create({
email: req.body.email,
});
// Save the customer.id in your database alongside your user.
// We're simulating authentication with a cookie.
res.cookie('customer', customer.id, { maxAge: 900000, httpOnly: true });
res.send({ customer: customer });
});
app.post('/create-subscription', async (req, res) => {
// Simulate authenticated user. In practice this will be the
// Stripe Customer ID related to the authenticated user.
const customerId = req.cookies['customer'];
// Create the subscription
const priceId = req.body.priceId;
try {
const subscription = await stripe.subscriptions.create({
customer: customerId,
items: [{
price: priceId,
}],
payment_behavior: 'default_incomplete',
expand: ['latest_invoice.payment_intent'],
});
res.send({
subscriptionId: subscription.id,
clientSecret: subscription.latest_invoice.payment_intent.client_secret,
});
} catch (error) {
return res.status(400).send({ error: { message: error.message } });
}
});
app.get('/invoice-preview', async (req, res) => {
const customerId = req.cookies['customer'];
const priceId = process.env[req.query.newPriceLookupKey.toUpperCase()];
const subscription = await stripe.subscriptions.retrieve(
req.query.subscriptionId
);
const invoice = await stripe.invoices.retrieveUpcoming({
customer: customerId,
subscription: req.query.subscriptionId,
subscription_items: [ {
id: subscription.items.data[0].id,
price: priceId,
}],
});
res.send({ invoice });
});
app.post('/cancel-subscription', async (req, res) => {
// Cancel the subscription
try {
const deletedSubscription = await stripe.subscriptions.del(
req.body.subscriptionId
);
res.send({ subscription: deletedSubscription });
} catch (error) {
return res.status(400).send({ error: { message: error.message } });
}
});
app.post('/update-subscription', async (req, res) => {
try {
const subscription = await stripe.subscriptions.retrieve(
req.body.subscriptionId
);
const updatedSubscription = await stripe.subscriptions.update(
req.body.subscriptionId, {
items: [{
id: subscription.items.data[0].id,
price: process.env[req.body.newPriceLookupKey.toUpperCase()],
}],
}
);
res.send({ subscription: updatedSubscription });
} catch (error) {
return res.status(400).send({ error: { message: error.message } });
}
});
app.get('/subscriptions', async (req, res) => {
// Simulate authenticated user. In practice this will be the
// Stripe Customer ID related to the authenticated user.
const customerId = req.cookies['customer'];
const subscriptions = await stripe.subscriptions.list({
customer: customerId,
status: 'all',
expand: ['data.default_payment_method'],
});
res.json({subscriptions});
});
app.post(
'/webhook',
bodyParser.raw({ type: 'application/json' }),
async (req, res) => {
// Retrieve the event by verifying the signature using the raw body and secret.
let event;
try {
event = stripe.webhooks.constructEvent(
req.body,
req.header('Stripe-Signature'),
process.env.STRIPE_WEBHOOK_SECRET
);
} catch (err) {
console.log(err);
console.log(`⚠️ Webhook signature verification failed.`);
console.log(
`⚠️ Check the env file and enter the correct webhook secret.`
);
return res.sendStatus(400);
}
// Extract the object from the event.
const dataObject = event.data.object;
// Handle the event
// Review important events for Billing webhooks
// https://stripe.com/docs/billing/webhooks
// Remove comment to see the various objects sent for this sample
switch (event.type) {
case 'invoice.payment_succeeded':
if(dataObject['billing_reason'] == 'subscription_create') {
// The subscription automatically activates after successful payment
// Set the payment method used to pay the first invoice
// as the default payment method for that subscription
const subscription_id = dataObject['subscription']
const payment_intent_id = dataObject['payment_intent']
// Retrieve the payment intent used to pay the subscription
const payment_intent = await stripe.paymentIntents.retrieve(payment_intent_id);
try {
const subscription = await stripe.subscriptions.update(
subscription_id,
{
default_payment_method: payment_intent.payment_method,
},
);
console.log("Default payment method set for subscription:" + payment_intent.payment_method);
} catch (err) {
console.log(err);
console.log(`⚠️ Failed to update the default payment method for subscription: ${subscription_id}`);
}
};
break;
case 'invoice.payment_failed':
// If the payment fails or the customer does not have a valid payment method,
// an invoice.payment_failed event is sent, the subscription becomes past_due.
// Use this webhook to notify your user that their payment has
// failed and to retrieve new card details.
break;
case 'invoice.finalized':
// If you want to manually send out invoices to your customers
// or store them locally to reference to avoid hitting Stripe rate limits.
break;
case 'customer.subscription.deleted':
if (event.request != null) {
// handle a subscription cancelled by your request
// from above.
} else {
// handle subscription cancelled automatically based
// upon your subscription settings.
}
break;
case 'customer.subscription.trial_will_end':
// Send notification to your user that the trial will end
break;
default:
// Unexpected event type
}
res.sendStatus(200);
}
);
app.listen(4242, () => console.log(`Node server listening on port http://localhost:${4242}!`));
@@ -0,0 +1,15 @@
{
"name": "webhook",
"version": "1.0.0",
"description": "",
"main": "webhook.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"stripe": "^17.3.1"
}
}
@@ -0,0 +1,54 @@
// This is your test secret API key.
const stripe = require('stripe')('sk_test_51OIu21J7BKlr2pgsABfPagNLQmRYdn8wSDNOj9ph6q0T6ThchqyfRC585qp5iG1bHM3MrxnTHOUGQRGhZ4K6h5Sg00DmDdAv7Q');
// 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
// whsec_ce937ab59c83dcecc659324f312e6044cc80246e3932d9b93bee27a3a6a513ef
const endpointSecret = 'whsec_ce937ab59c83dcecc659324f312e6044cc80246e3932d9b93bee27a3a6a513ef';
const express = require('express');
const app = express();
app.post('/webhook', express.raw({type: 'application/json'}), (request, response) => {
let event = request.body;
// 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);
}
}
// Handle the event
switch (event.type) {
case 'payment_intent.succeeded':
const paymentIntent = event.data.object;
console.log(`PaymentIntent for ${paymentIntent.amount} was successful!`);
// Then define and call a method to handle the successful payment intent.
// handlePaymentIntentSucceeded(paymentIntent);
break;
case 'payment_method.attached':
const paymentMethod = event.data.object;
console.log(paymentMethod);
// Then define and call a method to handle the successful attachment of a PaymentMethod.
// handlePaymentMethodAttached(paymentMethod);
break;
default:
// Unexpected event type
console.log(`Unhandled event type ${event.type}.`);
}
// Return a 200 response to acknowledge receipt of the event
response.send();
});
app.listen(4242, () => console.log('Running on port 4242'));