almost there

This commit is contained in:
tavo-wasd 2024-08-13 07:39:34 -06:00
parent 4f12ac560e
commit ec0800dadd
5 changed files with 122 additions and 175 deletions

View file

@ -1,11 +1,33 @@
function isFormValid(form) {
return form.checkValidity();
// TODO
//
// 1. See if I can stop using hosted buttons and use
// https://developer.paypal.com/integration-builder/ instead
// to use components=buttons only. Or, Try to load both,
// components=buttons,hosted-buttons etc.
//
// 2. Try to disable asking for shipping info (although could be
// useful to mark as sent).
//
// 3. Read about IPN and Webhooks to automate registering process.
const PayPalSdkOneTime = "";
const PayPalSdkSub = "";
const clientId = "";
const OneTimePID = "";
const PlanID = "";
function loadScript(url, callback) {
const script = document.createElement('script');
script.src = url;
script.onload = callback;
script.onerror = () => {
console.error(`Script load error: ${url}`);
};
document.head.appendChild(script);
}
function removePayPalElement() {
const element = document.getElementById('paypal-button-container');
element.innerHTML = '';
element.style.display = 'none';
function loadPayPalSDK(url, callback) {
loadScript(url, callback);
}
function hideDialog() {
@ -14,105 +36,64 @@ function hideDialog() {
document.getElementById('openDialogButton').style.display = 'block';
}
function renderPaypalElement() {
const element = document.getElementById('paypal-button-container');
element.innerHTML = '';
element.style.display = 'block';
paypal.Buttons({
style: {color: 'blue', shape: 'pill', label: 'pay', height: 40},
// Call your server to set up the transaction
createOrder: function(data, actions) {
return fetch('/demo/checkout/api/paypal/order/create/', {
method: 'post'
}).then(function(res) {
return res.json();
}).then(function(orderData) {
return orderData.id;
});
},
// Call your server to finalize the transaction
onApprove: function(data, actions) {
return fetch('/demo/checkout/api/paypal/order/' + data.orderID + '/capture/', {
method: 'post'
}).then(function(res) {
return res.json();
}).then(function(orderData) {
var errorDetail = Array.isArray(orderData.details) && orderData.details[0];
// (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
return actions.restart();
}
// (2) Other non-recoverable errors -> Show a failure message
if (errorDetail) {
var msg = 'Sorry, your transaction could not be processed.';
if (errorDetail.description) msg += '\n\n' + errorDetail.description;
if (orderData.debug_id) msg += ' (' + orderData.debug_id + ')';
return alert(msg); // TODO show a prettier message
}
// (3) Successful transaction -> Show confirmation or thank you
// Grab transaction.status and transaction.id, call up php and save it in db.
// var transaction = orderData.purchase_units[0].payments.captures[0];
// alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');
// Replace the above to show a success message within this page, e.g.
element.innerHTML = '';
element.innerHTML = '<h3>Thank you for your payment!</h3>';
document.getElementById('mainForm').submit();
});
}
}).render('#paypal-button-container');
}
document.getElementById('openDialogButton').addEventListener('click', () => {
function showDialog() {
document.getElementById('overlay').style.display = 'block';
document.getElementById('dialog').style.display = 'block';
document.getElementById('openDialogButton').style.display = 'none';
});
document.getElementById('submitDialogButton').addEventListener('click', () => {
const form = document.getElementById('mainForm');
['name', 'email', 'phone'].forEach(id => {
const input = document.createElement('input');
input.type = 'hidden';
input.name = id;
input.value = document.getElementById(id).value;
form.appendChild(input);
});
if (isFormValid(form)) {
document.getElementById('submitDialogButton').style.display = 'none';
document.getElementById('error-message').style.display = 'none';
renderPaypalElement();
} else {
document.getElementById('submitDialogButton').style.display = 'inline';
document.getElementById('error-message').style.display = 'block';
removePayPalElement();
}
// const orderIDInput = document.createElement('input');
// orderIDInput.type = 'hidden';
// orderIDInput.name = 'paypalOrderID';
// orderIDInput.value = paypalOrderID;
// form.appendChild(orderIDInput);
// form.submit();
function togglePaymentMethod(selectedButtonId) {
// Deselect all buttons and hide all PayPal buttons
document.querySelectorAll('#method-button-container button').forEach(button => {
button.classList.remove('active');
});
document.querySelectorAll('#paypal-button-container > div').forEach(div => {
div.classList.remove('active');
});
// Select the clicked button and show the corresponding PayPal button
const selectedButton = document.getElementById(selectedButtonId);
selectedButton.classList.add('active');
if (selectedButtonId === 'showOneTimeButton') {
document.getElementById('paypal-button-container').classList.add('active');
document.getElementById('paypalOneTimeButton').classList.add('active');
loadPayPalSDK(PayPalSdkOneTime, () => {
paypal.HostedButtons({
hostedButtonId: OneTimePID,
}).render("#paypalOneTimeButton");
});
} else if (selectedButtonId === 'showSubButton') {
document.getElementById('paypal-button-container').classList.add('active');
document.getElementById('paypalSubButton').classList.add('active');
loadPayPalSDK(PayPalSdkSub, () => {
paypal.Buttons({
style: { shape: 'pill', color: 'black', layout: 'vertical', label: 'subscribe' },
createSubscription: function(data, actions) {
return actions.subscription.create({
plan_id: PlanID
});
},
onApprove: function(data, actions) {
alert(data.subscriptionID); // You can add optional success message for the subscriber here
}
}).render('#paypalSubButton'); // Renders the PayPal button
});
}
}
document.getElementById('showOneTimeButton').addEventListener('click', function() {
togglePaymentMethod('showOneTimeButton');
});
document.getElementById('showSubButton').addEventListener('click', function() {
togglePaymentMethod('showSubButton');
});
document.getElementById('openDialogButton').addEventListener('click', () => {
showDialog();
});
document.getElementById('cancelDialogButton').addEventListener('click', () => {
hideDialog();
});
document.addEventListener('click', (event) => {
const dialog = document.getElementById('dialog');
const openDialogButton = document.getElementById('openDialogButton');
// If the click is outside the dialog and not on the openDialogButton, hide the dialog
if (!dialog.contains(event.target) && !openDialogButton.contains(event.target)) {
hideDialog();
}
});

View file

@ -3,7 +3,7 @@
<head>
<title>Builder | CONEX.one </title>
<link rel="canonical" href="https://builder.conex.one">
<link rel='stylesheet' type='text/css' href='/style.css'>
<link rel='stylesheet' type='text/css' href='/static/css/style.css'>
<link rel="icon" href="favicon.png">
<meta name="description" content="Constructor de sitios web de CONEX.one">
<meta name="viewport" content="width=device-width, initial-scale=1">
@ -13,7 +13,6 @@
<link rel="stylesheet" href="/static/css/simplemde-dark.min.css">
<link rel="stylesheet" href="/static/css/style.css">
<script src="/static/js/simplemde.min.js"></script>
<script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD"></script>
</head>
<form action="submit.php" id="mainForm" method="post">
<div class="banner" style="background-image: url(/static/banner.jpg);">
@ -39,21 +38,17 @@
<input type="text" id="name" name="name" placeholder="Nombre" required>
<input type="email" id="email" name="email" placeholder="Correo electrónico" required>
<input type="tel" id="phone" name="phone" placeholder="Teléfono (Opcional)">
<div id="paypal-button-container"></div>
<button id="submitDialogButton" class="button-pay" type="button">$20 al año</button>
<div id="method-button-container">
<button id="showOneTimeButton" type="button">Pago Único</button>
<button id="showSubButton" type="button">Pago Automático</button>
<button id="cancelDialogButton" type="button">Cancelar</button>
</div>
<div id="paypal-button-container">
<div id="paypalOneTimeButton"></div>
<div id="paypalSubButton"></div>
</div>
</div>
</form>
<script>
var simplemde = new SimpleMDE({
element: document.getElementById("editor"),
toolbar: ["preview", "|", "heading", "bold", "italic", "unordered-list", "ordered-list", "|", "link", "image", "table"],
spellChecker: false,
});
simplemde.value("# Bienvenido a [Empresa]\n\nUbicados en [Dirección de la Empresa]\n\n✉ contacto@empresa.com\n☎ +506 8888 8888\n\n# Servicios\n\n| Servicio | Descripción | Monto |\n| -------- | ----------- | --------- |\n| Uno | Una | 1.000,00 |\n| Dos | Breve | 10.000,00 |\n| Tres | Explicación | 7.500,00 |\n\n![Imagen ejemplo](https://0x0.st/XWHZ.jpg)\n\n# Acerca de Nosotros\n\nEn [Empresa], nos especializamos en [breve descripción de tus servicios/productos]. Nuestro equipo está dedicado a ofrecer [propuesta de valor o punto de venta único].\n\n# Síguenos\n\n[Facebook](https://facebook.com) | [Instagram](https://instagram.com)\n");
document.getElementById('openDialogButton').addEventListener('click', () => {
document.getElementById('dialog').style.display = 'block';
});
</script>
<script src="/static/js/simplemde.config.js"></script>
<script src="/form.js"></script>
</html>

View file

@ -141,6 +141,8 @@ footer {
z-index: 1000;
border-radius: 10px;
text-align: left;
overflow: auto;
max-height: 80vh;
}
#dialog h2, #dialog p {
@ -201,24 +203,6 @@ button {
color: var(--color);
}
#dialog .button-pay{
border: 0px solid #000;
background: #008645;
font-weight: bold;
color: white;
}
#dialog .button-pay:hover {
background: #006d38;
font-weight: bold;
color: white;
}
#paypal-button-container {
display: none;
padding: 0.5em 0;
}
#openDialogButton {
position: fixed;
bottom: 2em;
@ -241,6 +225,28 @@ button {
border: 0;
}
#method-button-container button {
background-color: #ccc;
border: none;
padding: 10px 20px;
margin: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
#method-button-container button.active {
background-color: #007bff;
color: white;
}
#paypal-button-container > div {
display: none;
}
#paypal-button-container > div.active {
display: block;
}
/* Custom SimpleMDE styling */
.CodeMirror {
border-radius: 10px;

View file

@ -0,0 +1,9 @@
var simplemde = new SimpleMDE({
element: document.getElementById("editor"),
toolbar: ["preview", "|", "heading", "bold", "italic", "unordered-list", "ordered-list", "|", "link", "image", "table"],
spellChecker: false,
});
simplemde.value("# Bienvenido a [Empresa]\n\nUbicados en [Dirección de la Empresa]\n\n✉ contacto@empresa.com\n☎ +506 8888 8888\n\n# Servicios\n\n| Servicio | Descripción | Monto |\n| -------- | ----------- | --------- |\n| Uno | Una | 1.000,00 |\n| Dos | Breve | 10.000,00 |\n| Tres | Explicación | 7.500,00 |\n\n![Imagen ejemplo](https://0x0.st/XWHZ.jpg)\n\n# Acerca de Nosotros\n\nEn [Empresa], nos especializamos en [breve descripción de tus servicios/productos]. Nuestro equipo está dedicado a ofrecer [propuesta de valor o punto de venta único].\n\n# Síguenos\n\n[Facebook](https://facebook.com) | [Instagram](https://instagram.com)\n");
document.getElementById('openDialogButton').addEventListener('click', () => {
document.getElementById('dialog').style.display = 'block';
});

View file

@ -1,44 +0,0 @@
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$date = new DateTime();
$isoDate = $date->format(DateTime::ISO8601);
$directory = "submit/";
$filename = "$isoDate.md";
$filePath = $directory . $filename;
if (!is_dir($directory)) {
mkdir($directory, 0755, true);
}
$title = isset($_POST["title"]) ? $_POST["title"] : "";
$slogan = isset($_POST["slogan"]) ? $_POST["slogan"] : "";
$name = isset($_POST["name"]) ? $_POST["name"] : "";
$email = isset($_POST["email"]) ? $_POST["email"] : "";
$phone = isset($_POST["phone"]) ? $_POST["phone"] : "";
$phone = isset($_POST["paypalOrderID"]) ? $_POST["paypalOrderID"] : "";
$editorContent = isset($_POST["editor"]) ? $_POST["editor"] : "";
$editorContent = str_replace("\r\n", "\n", $editorContent); // Convert CRLF to LF
$editorContent = str_replace("\r", "\n", $editorContent); // Convert CR to LF
$content = <<<EOD
---
date: $isoDate
author: "$name <$email> <$phone>"
orderID: $paypalOrderID
title: "$title"
description: "$slogan"
layout: single
---
$editorContent
EOD;
$file = "$isoDate.md";
file_put_contents($filePath, $content);
echo "Done";
} else {
echo "Error";
}
?>