Jul 28, 2023
0
Level 7
STRIPE integration Laravel/Vue. - how to get customer details?
Hi,
I would like to be able to pass in my customer first_name and last_name and email so I can see which subscription relates to which client, can someone please help?
here is my frontend VUE:
<script setup>
import { loadStripe } from "@stripe/stripe-js";
import { ref, onMounted, computed } from "vue";
import { useUserStore } from "../store/UserStore";
import { useClientStore } from "../store/ClientStore";
import { useProfileStore } from "../store/ProfileStore";
import { usePostStore } from "../store/PostStore";
import { useRouter } from "vue-router";
import TextInput from "@/components/global/TextInput.vue";
import SelectInput from "@/components/global/SelectInput.vue";
import axios from "axios";
import TopNavigation from "@/components/structure/TopNavigation.vue";
const userStore = useUserStore();
const clientStore = useClientStore();
const router = useRouter();
const profileStore = useProfileStore();
const postStore = usePostStore();
let errors = ref([]);
let clientId = ref(null);
let firstName = ref(null);
let lastName = ref(null);
let email = ref(null);
let password = ref(null);
let confirmPassword = ref(null);
let clients = ref([]);
let stripe = ref(null); // Declare stripe as a reactive property
let cardElement = ref(null);
let transformedOptions = computed(() => {
return clients.value.map((client) => ({
value: client.id,
label: client.name,
}));
});
onMounted(async () => {
await clientStore.fetchClients();
clients.value = clientStore.clients;
stripe.value = await initializeStripe(); // Assign the initialized stripe value
const elements = stripe.value.elements(); // Get the Stripe elements instance
cardElement.value = elements.create("card");
cardElement.value.mount("#card-element");
});
const initializeStripe = async () => {
const stripe = await loadStripe(
"pk_test_51LGnwdH8B3O205oeNawhEVgb4g7R3iFEQjPk25ScCUvq0jYgv46VQCDH2tpDnJW08WYdjYzXNvDZYLB2oDUjavWd0044IrAwxH"
); // Replace with your Stripe publishable key
//const stripe = await loadStripe('pk_live_51LGnwdH8B3O205oeOdsDQZ10MwxqRwREqVLTHXBTKXddrsAV8KDBDCzHP7YW2jv4N4LdXYxEYon8guwdqWka92q900K5AijE1d');
return stripe;
};
async function handlePayment() {
try {
const { error, paymentMethod } = await stripe.value.createPaymentMethod({
type: "card",
card: cardElement.value,
});
if (error) {
console.log(error.message);
} else {
// Send the payment method ID to your server to handle the payment
console.log("Payment Method ID:", paymentMethod.id);
return paymentMethod.id;
}
} catch (e) {
console.log(e.message);
}
}
const register = async () => {
errors.value = [];
try {
let res = await axios.post("api/register", {
client_id: clientId.value,
first_name: firstName.value,
last_name: lastName.value,
email: email.value,
password: password.value,
password_confirmation: confirmPassword.value,
});
axios.defaults.headers.common["Authorization"] = "Bearer " + res.data.token;
console.log("Response Data: ", res);
const user = res.data.user;
userStore.setUserDetails(res);
console.log("UserStore: ", userStore);
await profileStore.fetchProfileById(userStore.id);
await postStore.fetchPostsByUserId(userStore.id);
const stripeInstance = await initializeStripe();
console.log("stripeInstance: ", stripeInstance);
// Make an API request to your backend to create a customer and subscription
const payment_id = await handlePayment();
const subscriptionResponse = await axios.post("api/create-subscription", {
user,
customerEmail: email.value,
customerName: firstName.value + " " + lastName.value,
priceId: "price_1NSmEQH8B3O205oeHPngASZm", // Replace with your actual Stripe price ID
paymentMethodId: payment_id,
});
console.log("subscriptionResponse: ", subscriptionResponse);
// Handle the subscription response as needed
const subscriptionId = subscriptionResponse.data.subscriptionId;
// ...
console.log("subscriptionId: ", subscriptionId);
router.push("/account/profile/" + userStore.id);
} catch (error) {
if (error.response && error.response.data && error.response.data.errors) {
errors.value = error.response.data.errors;
} else {
errors.value = ["An error occurred. Please try again."];
}
}
};
</script>
Here is my Laravel subscription controller:
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Laravel\Cashier\Cashier;
use Stripe\Stripe;
use Stripe\PaymentIntent;
use Illuminate\Support\Facades\Log;
use App\Models\Subscriptions;
class SubscriptionController extends Controller
{
public function create(Request $request)
{
// Set your Stripe secret key
Stripe::setApiKey('sk_test_51LGnwdH8B3O205oeVPUinr3kxVokSe3BUWXy9xw8uEfANYiqrLf0YiAJ4bl0ynjvkdYP45uTWa4wbmtjz8V5rxyc00kbia00cs');
try {
$amount = 6.99;
// Create a PaymentIntent
$paymentIntent = PaymentIntent::create([
'amount' => (int) $amount*100, // Amount in cents
'currency' => 'gbp',
"payment_method" => $request->input("paymentMethodId") ,
"confirm" => true
]);
$id = $paymentIntent->id;
Log::debug($id);
/*
$user = User::findOrFail($request->user['id']); // Assuming the authenticated user is available
Log::debug($user);
Log::debug($request->all());
Log::debug("Tariq");
$user->newSubscription('default', $request->plan)
->create($request->priceId, [
'email' => $request->customerEmail,
'name' => $request->customerName,
// Additional data fields can be set here
]);
Log::debug("Tariq-start1");
Log::debug($user);
Log::debug("Tariq-start2");
// Optionally, you can retrieve the subscription ID and return it in the response
$subscriptionId = $user->subscription('default')->id;
*/
//paymentMethodId
$user = User::findOrFail($request->user['id']); // Assuming the authenticated user is available
$user->stripe_id = $id;
$user->trial_ends_at = date('Y-m-d', strtotime(' + 1 month'));
$user->save();
$s = new Subscriptions();
$s->user_id = $user->id;
$s->name = $user->first_name;
$s->stripe_id = $id;
$s->stripe_status = "COMPLETED";
$s->stripe_price = $amount*100;
$s->save();
return response()->json([
'subscriptionId' => $s->id, // subscriptionId
]);
//Log::debug($paymentIntent);
//Log::debug($id);
} catch (\Exception $e) {
Log::debug($e);
}
return response()->json([
'message' => 'something went wrong at backend'
], 400);
}
}
Please or to participate in this conversation.