I would like to transfer the card details to mangopay
At first, I put the necessary code for the registration provided by the API
public function Registration($user)
{
$CardRegistration = new \MangoPay\CardRegistration();
$CardRegistration->UserId = $user->getIdMangopay();
$CardRegistration->Currency = "EUR";
$CardRegistration->CardType = "CB_VISA_MASTERCARD";
$Result = $Api->CardRegistrations->Create($CardRegistration);
}
then I call this function when submitting my form during a purchase
public function payment(Request $request, ApiUser $ApiUser): Response
{
$payment = new PaymentMethod();
$form = $this->createForm(RegistrationCard::class);
$form->handleRequest($request);
if ($form->isSubmitted()){
$name = $form->get('name')->getData();
$cardnumber = $form->get('cardnumber')->getData();
if($name){
$payment->setName($name);
}
if($cardnumber){
$payment->setCardNumber($cardnumber);
}
$ApiUser->Registration($form);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($payment);
$entityManager->flush();
return $this->redirectToRoute("profil");
}
return $this->render('home/payment.html.twig', [
'controller_name' => 'HomeController',
]);
}
Related
public function insertclients(Request $request)
{
$client = new Clients();
$client->client_name = $request->input('client_name');
$client->client_society = $request->input('client_society');
$client->client_email = $request->input('client_email');
$client->client_address = $request->input('client_address');
$client->client_phone = $request->input('client_phone');
$client->client_fix = $request->input('client_fix');
if ($this->nameclient($request->input('client_name')) < 1) {
$client->save();
return response()->json($client);
} else {
return response()->json('error', 'Client name already exists'); }
// return redirect('clients')->with('flash_message', 'Client Addedd!');
}
public function nameclient(Request $request)
{
//check count of client name
$count = Clients::where('client_name', $request->input('client_name'))->get();
$clicount = $count->count();
return $clicount;
}
I have this method for add new client but i wanna check if the name don't repeat so i create other function who check the name of client and i call it in the ferst but doesn't work.
You are already sending the input with $this->nameclient($request->input('client_name')
so change your method to accept a string variable
public function nameclient($clientName)
{
return Clients::where('client_name', $clientName)->count();
}
Bonus:
Maybe this way it would be more readable
public function insertclients(Request $request)
{
if ($this->nameclient($request->input('client_name')) {
return response()->json('error', 'Client name already exists');
}
$client = new Clients();
$client->client_name = $request->input('client_name');
$client->client_society = $request->input('client_society');
$client->client_email = $request->input('client_email');
$client->client_address = $request->input('client_address');
$client->client_phone = $request->input('client_phone');
$client->client_fix = $request->input('client_fix');
$client->save();
return response()->json($client);
// return redirect('clients')->with('flash_message', 'Client Addedd!');
}
You can also use laravel Validation instead of using the method nameclient and add the other validation rules in it like required fields and such.
public function insertclients(Request $request)
{
$request->validate([
'client_name' => 'required|unique:clients|max:255',
]);
$client = new Clients();
$client->client_name = $request->input('client_name');
$client->client_society = $request->input('client_society');
$client->client_email = $request->input('client_email');
$client->client_address = $request->input('client_address');
$client->client_phone = $request->input('client_phone');
$client->client_fix = $request->input('client_fix');
$client->save();
return response()->json($client);
// return redirect('clients')->with('flash_message', 'Client Addedd!');
}
I'm trying to register a credit card with MangoPay.
I've installed the mangopay/php-sdk-v2 package.
To register a credit card, it needs three steps.
Create a token of the card
Post card info (using a url created by the token) that will render a string that start with data=
Add the registered card to the MangoPay user
// ProfilController.php
/**
* #Route("/payment/{id}", name="payment")
* * #param int $id
*/
public function payment(Request $request, ApiUser $ApiUser, $id): Response
{
$returnUrl = "";
$user = $this->userRepository->findOneBy(['id' => $id]);
$userId = $user->getIdMangopay();
$registration = $ApiUser->Registration($userId);
if($request->request->count() > 0){
$payment = new PaymentMethod();
$payment->setName($request->request->get('name'));
$payment->setCardNumber($request->request->get('cardNumber'));
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($payment);
$entityManager->flush();
$registrationCard = $ApiUser->RegistrationCard($registration, $request);
$returnUrl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . $_SERVER['HTTP_HOST'];
$returnUrl .= '/profil';
}
return $this->render('home/payment.html.twig', [
'CardRegistrationUrl' => $registration->CardRegistrationURL,
'Data' => $registration->PreregistrationData,
'AccessKeyRef' => $registration->AccessKey,
'returnUrl' => $returnUrl,
]);
}
The Registration and ResitrationCard functions come from the ApiUser file:
// ApiUser.php
public function Registration($UserId)
{
$CardRegistration = new \MangoPay\CardRegistration();
$CardRegistration->UserId = $UserId;
$CardRegistration->Currency = "EUR";
$CardRegistration->CardType = "CB_VISA_MASTERCARD";
$Result = $this->mangoPayApi->CardRegistrations->Create($CardRegistration);
$this->registrationInfo = $Result;
$this->CardRegistrationUrl = $Result->CardRegistrationURL;
return $Result;
}
public function RegistrationCard($CardInfo)
{
$cardRegister = $this->mangoPayApi->CardRegistrations->Get($CardInfo->Id);
$cardRegister->RegistrationData = $_SERVER['QUERY'];
$updatedCardRegister = $this->mangoPayApi->CardRegistrations->Update($cardRegister);
return $Result;
}
I'm able to create the token of the card and get the data= string, but the problem is that I cannot do the last step.
It seems that I cannot enter into the if statement, so it doesn't register the card on the database and I cannot update the card information (3rd step).
The returnUrl, I can simply put it outside of the if statement to make it works, but I want to change it only if the form is valid.
How can I fix the statement? Why doesn't it enter into the if?
Please try to use the regular form validation process of Symfony, and let me know if this helps.
To do this, you need to customize the input name attribute for it to match the payment API config.
In your Type class:
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
// ...
->add('new-input-name-goes-here', TextType::class, [
'property_path' => '[data]'
]);
}
public function getBlockPrefix()
{
return '';
}
In my project I want to use the object created by my precedent form:
Here is the schema of my database:
My QuizController
public function creation(Request $request){
$quiz = new Quiz();
$user = $this->getUser();
$formQuiz = $this->createForm(QuizType::class, $quiz);
$formQuiz->handleRequest($request);
if ($formQuiz->isSubmitted() && $formQuiz->isValid() ) {
$quiz->setCreatedAt(new DateTimeImmutable());
$quiz->setCreatedBy($user);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($quiz);
$entityManager->flush();
return $this->redirectToRoute('creation_questions');
}
return $this->render('quiz/creation.html.twig', [
'formQuiz' => $formQuiz->createView(),
]);
}
And my QuestionController that must be connected with the quiz form
public function creation_questions(Request $request){
$quiz = ?
$question = new Questions();
$formQuestions = $this->createForm(QuestionType::class, $question);
$formQuestions->handleRequest($request);
if ($formQuestions->isSubmitted() && $formQuestions->isValid() ) {
$question->setCreatedAt(new DateTimeImmutable());
$question->setQuiz($quiz);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($question);
$entityManager->flush();
return $this->redirectToRoute('home');
}
return $this->render('questions/questions.html.twig', [
'formQuestion' => $formQuestions->createView()
]);
}
What do I have to write in place of the '?'?
You don't show your routing but you could use paramConverte "magic" from SensioFrameworkExtraBundle and do something like this.
/**
* #Route("/some-route/{id}", name="some_route_name")
*/
public function creation_questions(Request $request, Quiz $quiz)
{
$question = new Questions();
$formQuestions = $this->createForm(QuestionType::class, $question);
$formQuestions->handleRequest($request);
if ($formQuestions->isSubmitted() && $formQuestions->isValid()) {
$question->setCreatedAt(new DateTimeImmutable());
$question->setQuiz($quiz);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($question);
$entityManager->flush();
return $this->redirectToRoute('home');
}
return $this->render('questions/questions.html.twig', [
'formQuestion' => $formQuestions->createView()
]);
}
Where the {id} part of /someRoute/{id} is the Quiz Id. Symfony should automagically fetch the Quiz matching that id. Or you can be more explicit about how the param converter should interpret such a value. More info here https://symfony.com/bundles/SensioFrameworkExtraBundle/current/annotations/converters.html
Alternatively, you could pass the quiz id and fetch the quiz manually (less magic but totally legit).
/**
* #Route("/some-route/{id}", name="some_route_name")
*/
public function creation_questions(Request $request, int $id)
{
$entityManager = $this->getDoctrine()->getManager();
$quiz = $entityManager->getRepository(Quiz::class)->find($id);
$question = new Questions();
$formQuestions = $this->createForm(QuestionType::class, $question);
$formQuestions->handleRequest($request);
if ($formQuestions->isSubmitted() && $formQuestions->isValid()) {
$question->setCreatedAt(new DateTimeImmutable());
$question->setQuiz($quiz);
$entityManager->persist($question);
$entityManager->flush();
return $this->redirectToRoute('home');
}
return $this->render('questions/questions.html.twig', [
'formQuestion' => $formQuestions->createView()
]);
}
I try to send data from Postman to this function
public function new(Request $request): Response
{
$tag = new Tag();
$form = $this->createForm(TagType::class, $tag);
$form->submit($request->request->all());
if ($form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($tag);
$entityManager->flush();
$message = "Tag was successfully added";
return new JsonResponse(array("message: $message"));
}
$errors = $form->getErrors();
return new JsonResponse(array("message:$errors"));
}
If i send data as 'form-data' i can save it to database.
But i can't understand how to accept 'raw' Json 'application/json'
I can only manually take value from Request with
$tagTitle = $request->query->get('title');
And i can't do it with some FOSUserBundle etc.
I can use only jms/serializer. If i will need it.
You need to fetch the json from $request->getContent() first:
public function new(Request $request): Response
{
$tag = new Tag();
$form = $this->createForm(TagType::class, $tag);
$form->submit(json_decode($request->getContent(), true));
if ($form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($tag);
$entityManager->flush();
$message = "Tag was successfully added";
return new JsonResponse(array("message: $message"));
}
$errors = $form->getErrors();
return new JsonResponse(array("message:$errors"));
}
How to retrive values of posted form, for example in controller i check if is any username already if it redirect back to route which render the form, but how to retrive the last post values to not fill data of this form again.
example of controle:
/**
* #Route("/dystrybutor/pracownicy/add", name="dystrybutor_pracownicy_add")
*/
public function new(UserManagerInterface $userManager, EntityManagerInterface $entityManager, Request $request)
{
$pracownik = new Pracownik();
$form = $this->createForm(PracownikType::class, $pracownik);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$id = $this->getUser()->getDystrybutorId();
$username = $form["username"]->getData();
$password = $form["password"]->getData();
$email = $form["email"]->getData();
$userManager = $this->get('fos_user.user_manager');
$checkUser = $userManager->findUserByUsername($username);
if($checkUser) {
$this->addFlash(
'danger',
'Login jest już zajęty!'
);
return $this->redirectToRoute('dystrybutor_pracownicy_add');
}
else {
Generally you should just pass the $pracownik object to the action where you redirect to and then just pass it as argument when creating your form. This can be done with a lot of ways but I would suggest to use the forward method in your controller:
public function new(UserManagerInterface $userManager, EntityManagerInterface $entityManager, Request $request, Pracownik $pracownik = null){
$pracownik = $pracownik ?? new Pracownik();
$form = $this->createForm(PracownikType::class, $pracownik);
...
if($checkUser) {
$this->addFlash('danger','Login jest już zajęty!');
return $this->forward('App\Controller\DystrybutorController::new', array(
'pracownik' => $pracownik
));
}