Skip to content

Commit

Permalink
up
Browse files Browse the repository at this point in the history
  • Loading branch information
PhemcodeJay committed Dec 4, 2024
1 parent 31324c8 commit d1a05c4
Show file tree
Hide file tree
Showing 4 changed files with 377 additions and 22 deletions.
145 changes: 145 additions & 0 deletions AI-Analytics-Report.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
<?php
require 'vendor/autoload.php'; // Include OpenAI PHP SDK or use CURL if not installed

use Orhanerday\OpenAi\OpenAi;

$open_ai_key = 'your_openai_api_key';
$openAi = new OpenAi($open_ai_key);

// Example: Sending product sales data to OpenAI for analysis
$salesData = [
'weekly_sales' => $productMetrics,
'top_products' => $topProducts,
'inventory_metrics' => $inventoryMetrics,
];

// Convert data to JSON
$salesDataJson = json_encode($salesData);

// Construct the prompt
$prompt = "
Analyze the following sales data and provide insights:
$salesDataJson
- Identify trends in sales and inventory.
- Suggest actions to improve performance.
- Highlight any anomalies or concerns.
";

$response = $openAi->completion([
'model' => 'gpt-4',
'prompt' => $prompt,
'temperature' => 0.7,
'max_tokens' => 1000,
'top_p' => 1.0,
'frequency_penalty' => 0.0,
'presence_penalty' => 0.0,
]);

// Decode the response
$responseData = json_decode($response, true);
$insights = $responseData['choices'][0]['text'] ?? 'No insights found.';

// Display insights on the dashboard
echo "<h2>AI Analysis</h2>";
echo "<div>" . nl2br(htmlspecialchars($insights)) . "</div>";
?>


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Analysis Results</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
color: #333;
}
header {
background: #007bff;
color: #fff;
padding: 10px 20px;
text-align: center;
}
main {
padding: 20px;
}
.analysis-container {
margin: 0 auto;
max-width: 800px;
background: #fff;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
border-radius: 8px;
padding: 20px;
}
.analysis-container h2 {
color: #007bff;
}
.analysis-result {
background: #f9f9f9;
padding: 15px;
border: 1px solid #ddd;
border-radius: 8px;
margin-bottom: 15px;
}
.loading {
text-align: center;
color: #666;
}
</style>
</head>
<body>
<header>
<h1>Dynamic Data Analysis</h1>
</header>
<main>
<div class="analysis-container">
<h2>Analysis Results</h2>
<div id="results" class="loading">Loading analysis...</div>
</div>
</main>
<script>
// Fetch data dynamically (replace the URL with your server endpoint)
async function fetchAnalysis() {
const resultsContainer = document.getElementById('results');
try {
const response = await fetch('https://your-server-endpoint/api/analyze', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_OPENAI_API_KEY' // Add your server-side key
},
body: JSON.stringify({
query: "Analyze this data",
data: "Sample dynamic data from your database" // Replace with real data
})
});

if (!response.ok) {
throw new Error(`Error: ${response.status}`);
}

const analysis = await response.json();

// Display the analysis
resultsContainer.innerHTML = '';
analysis.results.forEach((item, index) => {
const resultDiv = document.createElement('div');
resultDiv.className = 'analysis-result';
resultDiv.innerHTML = `<strong>Result ${index + 1}:</strong> <p>${item}</p>`;
resultsContainer.appendChild(resultDiv);
});
} catch (error) {
resultsContainer.innerHTML = `<p>Error loading analysis: ${error.message}</p>`;
}
}

// Initialize the analysis on page load
window.onload = fetchAnalysis;
</script>
</body>
</html>
26 changes: 4 additions & 22 deletions pay.php
Original file line number Diff line number Diff line change
Expand Up @@ -186,16 +186,6 @@ function getExchangeRates($baseCurrency = 'USD') {
<?php endforeach; ?>
</ul>

<!-- Subscription Plan Selection -->
<div class="form-group">
<label for="planSelect<?= $planKey ?>">Choose Your Plan:</label>
<select id="planSelect<?= $planKey ?>" name="planSelect" onchange="updatePlan('<?= $planKey ?>')">
<option value="P-7E210255TM029860GM5HYC4A">Enterprise</option>
<option value="P-6TP94103DT2394623M5HYFKY">Growth</option>
<option value="P-92V01000GH171635WM5HYGRQ">Starter</option>
</select>
</div>

<!-- PayPal Button Container for each plan -->
<div id="paypal-button-container-<?= $planKey ?>"></div>

Expand Down Expand Up @@ -224,16 +214,7 @@ function getExchangeRates($baseCurrency = 'USD') {
<script src="https://www.paypal.com/sdk/js?client-id=AZYvY1lNRIJ-1uKK0buXQvvblKWefjilgca9HAG6YHTYkfFvriP-OHcrUZsv2RCohiWCl59FyvFUST-W&vault=true&intent=subscription" data-sdk-integration-source="button-factory"></script>

<script>
// Function to update the plan dynamically based on user selection
function updatePlan(planKey) {
var planSelect = document.getElementById('planSelect' + planKey);
var selectedPlanId = planSelect.value;

// Re-render the PayPal button with the selected plan
renderPaypalButton(planKey, selectedPlanId);
}

// Function to render the PayPal button based on the selected plan
// Function to render the PayPal button based on the selected plan ID
function renderPaypalButton(planKey, planId) {
// Destroy the previous PayPal button (if any)
if (paypal.Buttons !== undefined) {
Expand All @@ -259,9 +240,10 @@ function renderPaypalButton(planKey, planId) {
}).render('#paypal-button-container-' + planKey); // Renders the PayPal button inside the specified container
}

// Initial render for all plans
// Initial render for all plans with hardcoded plan IDs
<?php foreach ($pricingPlans as $planKey => $plan): ?>
renderPaypalButton('<?= $planKey ?>', 'P-7E210255TM029860GM5HYC4A');
// Render the PayPal button for each plan using the respective plan ID
renderPaypalButton('<?= $planKey ?>', 'P-7E210255TM029860GM5HYC4A'); // Replace with actual plan ID for each plan
<?php endforeach; ?>
</script>

Expand Down
107 changes: 107 additions & 0 deletions webhook-pay.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<?php
// Set your PayPal client ID and secret
$clientId = 'YOUR_CLIENT_ID';
$clientSecret = 'YOUR_CLIENT_SECRET';

// PayPal's webhook verification URL
$paypalWebhookUrl = 'https://api.paypal.com/v1/notifications/verify-webhook-signature';

// Webhook request body
$bodyReceived = file_get_contents('php://input');
$headers = getallheaders();

// PayPal sends a 'paypal-auth-algo' header which contains the signature algorithm used to generate the signature
$authAlgo = $headers['paypal-auth-algo'];
$certUrl = $headers['paypal-cert-url'];
$transmissionId = $headers['paypal-transmission-id'];
$transmissionSig = $headers['paypal-transmission-sig'];
$timestamp = $headers['paypal-transmission-time'];

// Prepare the verification request payload
$verificationData = [
'auth_algo' => $authAlgo,
'cert_url' => $certUrl,
'transmission_id' => $transmissionId,
'transmission_sig' => $transmissionSig,
'transmission_time' => $timestamp,
'webhook_id' => 'YOUR_WEBHOOK_ID',
'webhook_event' => json_decode($bodyReceived),
];

// Send the verification request to PayPal API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $paypalWebhookUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($verificationData));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Basic ' . base64_encode($clientId . ':' . $clientSecret),
]);

$response = curl_exec($ch);
curl_close($ch);

$verificationResponse = json_decode($response, true);

// If PayPal verifies the webhook, process the event
if ($verificationResponse['verification_status'] === 'SUCCESS') {
$event = json_decode($bodyReceived, true);

// Check the event type
if ($event['event_type'] === 'PAYMENT.SALE.COMPLETED') {
// Handle the payment confirmation (payment has been successfully processed)
$subscriptionId = $event['resource']['billing_agreement_id']; // Get subscription ID from the event
$payerId = $event['resource']['payer']['payer_info']['payer_id'];

// Call your database to activate the subscription
activateSubscription($subscriptionId, $payerId);
}

if ($event['event_type'] === 'BILLING.SUBSCRIPTION.CREATED') {
// Handle the subscription creation
$subscriptionId = $event['resource']['id']; // Subscription ID
$subscriberEmail = $event['resource']['subscriber']['email_address'];

// Call your database to save the subscription details and activate it
activateSubscription($subscriptionId, $subscriberEmail);
}

// Add additional event types as needed
} else {
// Verification failed
error_log('Webhook verification failed');
}

// Function to activate the subscription in your database using PDO
function activateSubscription($subscriptionId, $payerId) {
// Database connection using PDO
try {
$db = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Check if the subscription already exists
$stmt = $db->prepare("SELECT * FROM subscriptions WHERE subscription_id = :subscriptionId");
$stmt->bindParam(':subscriptionId', $subscriptionId);
$stmt->execute();

// If the subscription doesn't exist, insert it
if ($stmt->rowCount() === 0) {
$stmt = $db->prepare("INSERT INTO subscriptions (subscription_id, payer_id, status) VALUES (:subscriptionId, :payerId, 'active')");
$stmt->bindParam(':subscriptionId', $subscriptionId);
$stmt->bindParam(':payerId', $payerId);
$stmt->execute();
} else {
// Update the existing subscription status
$stmt = $db->prepare("UPDATE subscriptions SET status = 'active' WHERE subscription_id = :subscriptionId");
$stmt->bindParam(':subscriptionId', $subscriptionId);
$stmt->execute();
}

// Optionally send an email or do further processing
// mail($userEmail, "Subscription Activated", "Your subscription has been activated.");
} catch (PDOException $e) {
error_log('Database error: ' . $e->getMessage());
}
}
?>
Loading

0 comments on commit d1a05c4

Please sign in to comment.