Call shopware admin controller in backend from custom admin module in frontend
I have created the next admin controller to cancel stripe subscriptions:
File: plugins/ApiKeySubscriptionPlugin/src/Controller/SubscriptionController.php
#[Route(defaults: ['_routeScope' => ['api']])]
class SubscriptionController extends AbstractController
{
private EntityRepository $subscriptionRepository;
//public function __construct(ParameterBagInterface $params, LoggerInterface $logger)
public function __construct( EntityRepository $subscriptionRepository)
{
$this->subscriptionRepository = $subscriptionRepository;
}
#[Route(path: '/api/subscription/cancel', name: 'api.subscription.cancel', methods: ['POST'])]
public function cancelSubscription(Request $request, Context $context): JsonResponse
{
$data = json_decode($request->getContent(), true);
$subscriptionId = $data['subscriptionId'] ?? null;
if (!$subscriptionId) {
return new JsonResponse(['success' => false, 'message' => 'No subscription ID provided'], 400);
}
try {
// Initialize Stripe with the secret key securely from environment or parameter bag
//$stripeApiKey = $this->params->get('stripe.secret_key'); // Fetch from services.xml or .env
$stripeApiKey = $_ENV['STRIPE_API_KEY'];
if (!$stripeApiKey) {
throw new \Exception('Stripe API key is not set.');
}
Stripe::setApiKey($stripeApiKey); // Set your Stripe API key from .env file
// Retrieve the subscription from Stripe
$subscription = Subscription::retrieve($subscriptionId);
if (!$subscription) {
return new JsonResponse(['error' => 'Subscription not found!!!'], 404);
}
// Cancel the subscription immediately
$canceledSubscription = $subscription->cancel();
// Update your Shopware entity to reflect the cancellation
$data = [
'isActive' => false,
];
$this->updateSubscriptionByExternalId($subscriptionId, $data);
return new JsonResponse(['success' => true, 'subscription' => $canceledSubscription], 200);
} catch (\Exception $e) {
// Log the error or handle it accordingly
return new JsonResponse(['error' => $e->getMessage()], 500);
}
}
}
I wanna call cancelSubscription in the backend from a custom admin module in the frontend.
Therefore I have the next file with my vue component:
plugins/ApiKeySubscriptionPlugin/src/Resources/app/administration/src/module/page/apikey-subscription-list/index.js
And the next functions:
async onCancelSubscription(item) {
console.log('Cancel Subscription clicked for:', item);
// Ensure subscriptionId is properly accessed
const subscriptionId = item.stripeSubscriptionId;
if (!subscriptionId) {
console.error('No subscription ID found in the provided item');
return;
}
// Optional: Show a confirmation dialog
// Use the native browser confirm dialog for now
const confirmed = window.confirm(`Are you sure you want to cancel the subscription for "${item.stripeSubscriptionId}"?`);
if (!confirmed) {
return;
}
this.isLoading = true;
try {
const token = await this.getOAuthToken();
if (!token) {
throw new Error('Failed to retrieve OAuth token');
}
const response = await fetch('/api/subscription/cancel', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
body: JSON.stringify({
subscriptionId: subscriptionId
})
});
const result = await response.json(); // Get the raw response as json
console.log('Raw Response Json:', result);
if (result.success) {
console.log('Subscription canceled successfully!!!');
} else {
throw new Error(result.message || 'Unknown error occurred');
}
// Refresh the list
this.getList();
} catch (error) {
console.error('Error canceling subscription:', error);
} finally {
this.isLoading = false;
}
},
async getOAuthToken() {
const url = 'http://localhost:8080/api/oauth/token';
const data = {
client_id: "SWIAUWP3NFDDAXRYEGNVT0WWWW",
client_secret: "NXRjUXZBNTU4SEQ4cXNtd2I5VldUSDBCOGJPWndSTVlXampLNWW",
grant_type: "client_credentials"
};
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error(`Failed to retrieve token: ${response.statusText}`);
console.log(`Failed to retrieve token: ${response.statusText}`);
}
const result = await response.json();
// console.log('OAuth Token:', result.access_token);
return result.access_token;
} catch (error) {
console.error('Error retrieving OAuth token:', error);
return null;
}
}
How can avoid to expose in the browser my client_secret and client_id ?