Ethereum Transfer token via smart contract - php

I am using web3p/ethereum-tx,web3p/web3.php for transfer ERC-1155 token.I attached a image like that image i want transaction method.
My code is below,
$eth->getTransactionCount($from,function($err,$data) use (&$from_addr_nonce){
$from_addr_nonce = gmp_intval($data->value);
});
$from_addr_nonce = Utils::toHex($from_addr_nonce,true);
$web3 = new Web3($binance_url);
$eth = $web3->eth;
$eth->gasPrice(function ($err, $resp) use (&$gasP) {
if ($err !== null) {
throw new \Exception($err->getMessage());
}
$gasP = $resp;
});
$params = [
'nonce' => $from_addr_nonce,
'from' => $from,
'to' => $contractAddress,
'data' => $data
];
// $contract->at($contractAddress)->estimateGas('transfer', $address, $params, function ($err, $gas) use (&$es) {
// if ($err !== null) {
// throw new \Exception($err->getMessage());
// }
// $es = $gas;
// });
$data = "0x".$contract->getData('transfer',$user_wallet->address,1);
//$data = "0x".$contract->mintNFT($from, $nftMint->token_id);
$transaction = new EthTransaction([
'nonce' => $from_addr_nonce,
'from' => $from,
'to' => $contractAddress,
'gas' => $gasP,
'gasPrice' => sprintf('0x%s', $gasP->toHex()),
'gasLimit' => sprintf('0x%s', '895D0'),
'value' => "0x0",
// 'value' =>$amount,
'chainId' => $chain_id,
'data' => $data,
]);
$signedTx = $transaction->sign($privKey);
$txId = '';
// Sending transaction to the blockchain
$contract->eth->sendRawTransaction(sprintf('0x%s', $signedTx), function ($err, $tx) use (&$txId) {
if ($err !== null) {
throw new \Exception($err->getMessage());
}
$txId = $tx;
});
I dont know how to pass tokenid and corresponding quantity.In the getdata function instead of amount i need token id to be pass.

Related

Stripe Checkout from Legacy to new migration not working

I have migrated my Stripe checkout from legacy version to the new one. The payment does work, but the success redirect URL as well as the DB update does not work.
When I send the request I get redirected to my main page instead of the user subscription page.
Also I do get the error:
Could not determine the URL to request: StripeCustomer instance has invalid ID: (no ID)
I already did some research and also visited the migration documentation from Stripe:
https://stripe.com/docs/payments/checkout/migration
But I do not get the error.
My guess is it is between the lines:
//$payer_id = $customer->id;
$payer_email = $customer->email;
$updateTrx = $trx->update([
'total_price' => $total,
'payment_gateway_id' => $payment_gateway_id,
'payment_id' => $payment_id,
//'payer_id' => $payer_id,
'payer_email' => $payer_email,
'status' => 2,
]);
if ($updateTrx) {
CheckoutController::updateSubscription($trx);
toastr()->success(lang('Payment made successfully', 'checkout'));
return redirect()->route('user.subscription');
}
from:
<?php
namespace App\Http\Controllers\Frontend\Gateways;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Frontend\User\CheckoutController;
use Exception;
use Illuminate\Http\Request;
use Stripe\Checkout\Session;
use Stripe\Customer;
use Stripe\Stripe;
class StripeCheckoutController extends Controller
{
public static function process($trx)
{
if ($trx->status != 0) {
$data['error'] = true;
$data['msg'] = lang('Invalid or expired transaction', 'checkout');
return json_encode($data);
}
if ($trx->plan->interval == 0) {
$planInterval = '(Monthly)';
} elseif ($trx->plan->interval == 1) {
$planInterval = '(Yearly)';
} elseif ($trx->plan->interval == 2) {
$planInterval = '(Lifetime)';
}
$paymentName = "Payment for subscription " . $trx->plan->name . " Plan " . $planInterval;
$gatewayFees = ($trx->total_price * paymentGateway('stripe_checkout')->fees) / 100;
$totalPrice = round(($trx->total_price + $gatewayFees), 2);
$priceIncludeFees = str_replace('.', '', ($totalPrice * 100));
$paymentDeatails = [
'customer_email' => $trx->user->email,
'payment_method_types' => [
'card',
],
'line_items' => [[
'price_data' => [
'currency' => currencyCode(),
'unit_amount' => $priceIncludeFees,
'product_data' => [
'name' => settings('website_name'),
'description' => $paymentName,
],
],
'quantity' => 1,
]],
'mode' => 'payment',
'cancel_url' => route('user.subscription'),
'success_url' => route('ipn.stripe_checkout') . '?session_id={CHECKOUT_SESSION_ID}',
];
try {
Stripe::setApiKey(paymentGateway('stripe_checkout')->credentials->secret_key);
$session = Session::create($paymentDeatails);
if ($session) {
$trx->update(['fees_price' => $gatewayFees, 'payment_id' => $session->id]);
$data['error'] = false;
$data['redirectUrl'] = $session->url;
return json_encode($data);
}
} catch (\Exception $e) {
$data['error'] = true;
$data['msg'] = $e->getMessage();
return json_encode($data);
}
}
public function ipn(Request $request)
{
$session_id = $request->session_id;
try {
Stripe::setApiKey(paymentGateway('stripe_checkout')->credentials->secret_key);
$trx = \App\Models\Transaction::where([['user_id', userAuthInfo()->id], ['payment_id', $session_id], ['status', 1]])->first();
if (is_null($trx)) {
throw new Exception(lang('Invalid or expired transaction', 'checkout'));
}
$session = Session::retrieve($session_id);
//if ($session->payment_status == "paid") {
if ($session->payment_status == "paid") {
$customer = Customer::retrieve($session->customer);
$total = ($trx->total_price + $trx->fees_price);
$payment_gateway_id = paymentGateway('stripe_checkout')->id;
$payment_id = $session->id;
//$payer_id = $customer->id;
$payer_email = $customer->email;
$updateTrx = $trx->update([
'total_price' => $total,
'payment_gateway_id' => $payment_gateway_id,
'payment_id' => $payment_id,
//'payer_id' => $payer_id,
'payer_email' => $payer_email,
'status' => 2,
]);
if ($updateTrx) {
CheckoutController::updateSubscription($trx);
toastr()->success(lang('Payment made successfully', 'checkout'));
return redirect()->route('user.subscription');
}
} else {
throw new Exception(lang('Payment failed', 'checkout'));
}
} catch (\Exception $e) {
toastr()->error($e->getMessage());
return redirect()->route('home');
}
}
}

How to validate if user already exists?

I want to validate if it already exists in the DB, so then show an error message. But I am always getting user already exists in both cases. How can I fix it?
Below is my code:
public function add(Request $request)
{
$request_data = $request->all();
$customer_ids = $request_data['ids'];
$campaigns_id = $request_data['campaigns_id'];
$customer_id_array = explode(',', $customer_ids);
$whereIn = $customer_id_array;
$check_customer = Participant::where('id', $campaigns_id)->whereIn('customer_id', $whereIn)->get();
if (!empty($check_customer)) {
return ['code' => 402, 'status' => 'error', 'data' => $check_customer, 'message' => 'Customer Already Exists'];
}
foreach ($customer_id_array as $key => $value) {
$participantObj = new Participant;
$participantObj['customer_id'] = $value;
$participantObj->campaign_id = $campaigns_id;
// $participantObj->pin_number = $this->randomNumber(3).''.$key;
$data = $participantObj;
$data ->save();
}
return['code' => 200, 'status' => 'success'];
}
Change this line
if (!empty($check_customer)) {
to
if ($check_customer->isNotEmpty()) {

Call to undefined method createMonthlySubscription()

I am using https://github.com/srmklive/laravel-paypal package and I try to use PayPal recurring method for monthly subscribes, it return error below:
Call to undefined method Srmklive\PayPal\Services\ExpressCheckout::createMonthlySubscription()
Code
//controller head
use Srmklive\PayPal\Services\ExpressCheckout;
use Srmklive\PayPal\Services\AdaptivePayments;
public function getExpressCheckout(Request $request)
{
$recurring = ($request->get('mode') === 'recurring') ? true : false;
$cart = $this->getCheckoutData($recurring);
try {
$response = $this->provider->setExpressCheckout($cart, $recurring);
return redirect($response['paypal_link']);
} catch (\Exception $e) {
$invoice = $this->createInvoice($cart, 'Invalid');
session()->put(['code' => 'danger', 'message' => "Error processing PayPal payment for Order $invoice->id!"]);
}
}
public function getExpressCheckoutSuccess(Request $request)
{
// dd($request->all());
$Itemm = Type::where('id', $request->input('type_id'))->first();
$recurring = ($request->get('mode') === 'recurring') ? true : false;
$token = $request->get('token');
$PayerID = $request->get('PayerID');
$cart = $this->getCheckoutData($recurring);
// Verify Express Checkout Token
$response = $this->provider->getExpressCheckoutDetails($token);
if (in_array(strtoupper($response['ACK']), ['SUCCESS', 'SUCCESSWITHWARNING'])) {
if ($recurring === true) {
$response = $this->provider->createMonthlySubscription($response['TOKEN'], $cart['item']['price'], $cart['subscription_desc']);
if (!empty($response['PROFILESTATUS']) && in_array($response['PROFILESTATUS'], ['ActiveProfile', 'PendingProfile'])) {
$status = 'Processed';
} else {
$status = 'Invalid';
}
} else {
// Perform transaction on PayPal
$payment_status = $this->provider->doExpressCheckoutPayment($cart, $token, $PayerID);
dd($payment_status);
$status = $payment_status['PAYMENTINFO_0_PAYMENTSTATUS'];
}
$invoice = $this->createInvoice($cart, $status);
if ($invoice->paid) {
session()->put(['code' => 'success', 'message' => "Order $invoice->id has been paid successfully!"]);
$user = Auth::user();
Mail::to($user->email)->send(new UserPlanActivated($user));
} else {
session()->put(['code' => 'danger', 'message' => "Error processing PayPal payment for Order $invoice->id!"]);
}
return redirect('/');
}
}
public function getAdaptivePay()
{
$this->provider = new AdaptivePayments();
$data = [
'receivers' => [
[
'email' => 'johndoe#example.com',
'amount' => 10,
'primary' => true,
],
[
'email' => 'janedoe#example.com',
'amount' => 5,
'primary' => false,
],
],
'payer' => 'EACHRECEIVER', // (Optional) Describes who pays PayPal fees. Allowed values are: 'SENDER', 'PRIMARYRECEIVER', 'EACHRECEIVER' (Default), 'SECONDARYONLY'
'return_url' => url('payment/success'),
'cancel_url' => url('payment/cancel'),
];
$response = $this->provider->createPayRequest($data);
dd($response);
}
public function notify(Request $request)
{
if (!($this->provider instanceof ExpressCheckout)) {
$this->provider = new ExpressCheckout();
}
$post = [
'cmd' => '_notify-validate',
];
$data = $request->all();
foreach ($data as $key => $value) {
$post[$key] = $value;
}
$response = (string) $this->provider->verifyIPN($post);
$ipn = new IPNStatus();
$ipn->payload = json_encode($post);
$ipn->status = $response;
$ipn->save();
// $user = Auth::user();
// Mail::to($user->email)->send(new UserPlanActivated($user));
}
protected function getCheckoutData($recurring = false)
{
$data = [];
$order_id = Invoice::all()->count() + 1;
$Itemm = Type::where('id', \Request::input('type_id'))->first();
// dd($Itemm['name']);
if ($recurring === true) {
$data['items'] = [
[
'name' => 'Monthly Subscription '.$Itemm['name'].' #'.$order_id,
'price' => $Itemm['price'],
'qty' => 1,
],
];
// $data['return_url'] = route('userec?mode=recurring');
$data['return_url'] = url('/paypal/ec-checkout-success?mode=recurring');
$data['subscription_desc'] = 'Monthly Subscription '.$Itemm['name'].' #'.$order_id;
} else {
$data['items'] = [
[
'name' => 'Monthly Subscription '.$Itemm['name'].' #'.$order_id,
'price' => $Itemm['price'],
'qty' => 1,
],
];
// $data['return_url'] = route('userec');
$data['return_url'] = url('/paypal/ec-checkout-success');
}
$data['invoice_id'] = $Itemm['name'].'_'.$order_id;
$data['invoice_description'] = "Order #$order_id Invoice";
$data['cancel_url'] = route('userpackages');
$total = 0;
foreach ($data['items'] as $item) {
$total += $item['price'] * $item['qty'];
}
$data['total'] = $total;
return $data;
}
protected function createInvoice($cart, $status)
{
$current = Carbon::now();
$expiredatetime = $current->addDays(30);
$invoice = new Invoice();
$invoice->user_id = Auth::user()->id;
$invoice->title = $cart['invoice_description'];
$invoice->price = $cart['total'];
$invoice->plan_expire = $expiredatetime->toDateTimeString();
collect($cart['items'])->each(function ($product) use ($invoice) {
$invoice->type_id = 3;
});
if (!strcasecmp($status, 'Completed') || !strcasecmp($status, 'Processed')) {
$invoice->paid = 1;
} else {
$invoice->paid = 0;
}
$invoice->save();
return $invoice;
}
Note
My error comes from this line in getExpressCheckoutSuccess function:
$response = $this->provider->createMonthlySubscription($response['TOKEN'], $cart['item']['price'], $cart['subscription_desc']);

laravel route findOrFail() problems

new with Laravel and I am trying to add a findOrFail on this specific route and it's giving me a hard time. What am I missing?
Route::get('/listing/{type}/{owner}/{id}/{address}', 'Properties\DisplayController#show');
Whats not working
Route::get('/listing/{type}/{owner}/{id}/{address}', function ($id) {
return Properties\DisplayController#show::findOrFail($id);
});
Error I am getting
Parse error: syntax error, unexpected '#', expecting ';'
controller/function I'm calling
public function show($type, $own, $id, $address = null)
{
$page = (object) $this->template;
$page->breadcrumbs[] = array('url' => 'javascript://', 'text' => 'Property Search', 'attribute' => array('data-component' => 'back'));
// Now lets query our server
$client = new GuzzleHttp\Client(['verify' => false ]);
$response = $client->get( env('LISTINGS_SERVER', 'https://listings.homicity.com') . '/property/' . $id);
$page->content = Property::parseResult($response->getBody());
$page->title = strtoupper(trim($page->content->address));
$page->breadcrumbs[] = array('text' => $page->title);
$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
$currency = 'CAD';
$raw = $formatter->parseCurrency($page->content->price, $currency );
$page->content->mortgage = Mortgage::stage(
false,
$raw
);
return view('property.display', compact('page'));
}
Thanks for the help!
To return directly on route:
Route::get('/listing/{type}/{owner}/{id}/{address}', function ($id) {
return App\YourModel::findOrFail($id);
});
https://laravel.com/docs/5.3/eloquent#retrieving-single-models
Since the model is on another server that we connect to using GuzzleHTTP, I could not put findOfFail() on the model.
Here is the edit to the controller. Added in the ['http_errors' => false] which prevents guzzle from returning http errors, and then a if statement using getStatusCode() to find if it was a error 500 or not.
public function show($type, $own, $id, $address = null)
{
$page = (object) $this->template;
$page->breadcrumbs[] = array('url' => 'javascript://', 'text' => 'Property Search', 'attribute' => array('data-component' => 'back'));
// Now lets query our server
$client = new GuzzleHttp\Client(['verify' => false ]);
$response = $client->get( env('LISTINGS_SERVER', 'https://listings.homicity.com') . '/property/' . $id, ['http_errors' => false]);
if ($response->getStatusCode() == "500") {
abort(404);
}
else {
$page->content = Property::parseResult($response->getBody());
$page->title = strtoupper(trim($page->content->address));
$page->breadcrumbs[] = array('text' => $page->title);
$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
$currency = 'CAD';
$raw = $formatter->parseCurrency($page->content->price, $currency );
$page->content->mortgage = Mortgage::stage(
false,
$raw
);
return view('property.display', compact('page'));
}
}

Phpunit test a method using a service

I'm trying to test a method which is using a service, and apparently it's not possible to test it like a normal method.
Does someone know what to do ?
I have this code for the moment :
namespace PlatformBundle\Tests;
use PlatformBundle\Controller\PaymentController;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class PaymentControllerTest extends WebTestCase
{
private $payment;
public function __construct() { parent::__construct(); $this->payment = new PaymentController(); }
public function testSendEmail()
{
$param = array(
'info' => array(
'email' => 'test#test.com', 'name' => 'test', 'fare' => 'test', 'id' => 'test'
)
);
$this->assertEquals(true, $this->invokeMethod($this->payment, 'sendEmail', $param));
}
/**
* Call protected/private method of a class.
*
* #param object &$object Instantiated object that we will run method on.
* #param string $methodName Method name to call
* #param array $parameters Array of parameters to pass into method.
*
* #return mixed Method return.
*/
public function invokeMethod(&$object, $methodName, array $parameters = array())
{
$reflection = new \ReflectionClass(get_class($object));
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method->invokeArgs($object, $parameters);
}
}
The controller where the method sendEmail is :
<?php
namespace PlatformBundle\Controller;
use PlatformBundle\Entity\Customer;
use PlatformBundle\Entity\Promocode;
use PlatformBundle\Entity\Transfer;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class PaymentController extends Controller
{
public function checkoutAction(Request $req)
{
if (! $req->isMethod('POST')) throw new AccessDeniedHttpException();
$info = $req->request->all();
$this->container->get('platform.formSecurity')->testAllInformation($info);
$this->saveCustomerIntoDb($info);
$info['payed'] = false;
$session = $req->getSession();
$session->set('info', $info);
$info['date'] = $this->container->get('platform.useful')->reverseDateFormat($info['date']);
return $this->render('PlatformBundle:Payment:checkout.html.twig', array(
'isIndex' => false,
'info' => $info,
'stripe' => $this->stripeConfig()
));
}
public function cancelAction(Request $req)
{
$req->getSession()->invalidate();
return $this->render('PlatformBundle:Payment:cancel.html.twig', array('isIndex' => false));
}
public function successAction(Request $req)
{
$session = $req->getSession();
$info = $session->get('info');
if ($info['payed']) {
$req->getSession()->invalidate();
if ($info === null) throw new Exception('Please contact us to make sure that the payment has been done and that your order has been taken into account.');
$this->saveTransferIntoDb($info);
$customer = $this->getDoctrine()->getManager()->getRepository('PlatformBundle:Customer')->findOneBy(array(
'email' => $info['email']
));
$transfer = $this->getDoctrine()->getManager()->getRepository('PlatformBundle:Transfer')->findOneBy(
array('customer' => $customer->getId()),
array('id' => 'desc'),
1
);
$info['id'] = $transfer->getId();
$info['date'] = $this->container->get('platform.useful')->reverseDateFormat($info['date']);
$this->sendEmail($info);
// if 5 payments done, send a promocode
if (is_int($customer->getPayments() / 5)) {
$this->createAndSendNewPromocode($customer);
}
return $this->render('PlatformBundle:Payment:success.html.twig', array(
'isIndex' => false,
'info' => $info
));
} else return new RedirectResponse('cancel');
}
private function sendEmail($info)
{
$mail = $this->container->get('platform.mail');
$mail->send(
$info['email'],
'You have ordered a transfer for Dublin',
$this->renderView('PlatformBundle:Mail:orderSucceed.html.twig', array('info' => $info)),
'info#dubair.ie'
);
$mail->send(
'info#airportcollections.net, info#dubair.ie, info#365onlineholidays.com',
'A customer ordered a transfer for Dublin',
$this->renderView('PlatformBundle:Mail:report.html.twig', array('info' => $info)),
'info#dubair.ie'
);
}
private function saveCustomerIntoDb($info)
{
// test if the customer already exist
$customersList = $this->getDoctrine()->getManager()->getRepository('PlatformBundle:Customer')
->findByEmail($info['email']);
$customerExists = (sizeof($customersList) == 1 ? true : false);
if ($customerExists) {
$customer = $customersList[0];
} else {
// Create the entity
$customer = new Customer();
// dateRegistration, country and ip are automatically created in the constructor
$customer->setEmail($info['email']);
$customer->setPayments(0);
}
$customer->setName($info['name']);
$customer->setPhone($info['phone']);
$em = $this->getDoctrine()->getManager();
$em->persist($customer);
$em->flush();
}
private function saveTransferIntoDb($info)
{
$customers = $this->getDoctrine()->getManager()->getRepository('PlatformBundle:Customer')
->findByEmail($info['email']);
$customer = $customers[0];
$customer->setPayments($customer->getPayments() + 1);
// make promocode outdated
if ($info['promocode'] != '') {
$promocode = $this->getDoctrine()->getManager()->getRepository('PlatformBundle:Promocode')
->findOneBy(array(
'value' => $info['promocode'],
'outdated' => 0,
'type' => 'short'
));
$promocode->setOutdated(1);
}
// test if transfer already exist
$transferList = $this->getDoctrine()->getManager()->getRepository('PlatformBundle:Transfer')->findBy(
array(
'customer' => $customer,
'pickup' => $info['pickup'],
'destination' => $info['destination'],
'pickupTime' => $info['pickupTime'],
'address' => $info['address']
), // criteria
array('pickup' => 'desc'), // sorting
5, // Limit
0 // Offset
);
// if transfer doesn't already exist, create it
if (sizeof($transferList) == 0) {
$transfer = new Transfer();
$transfer->setPickup($info['pickup']);
$transfer->setDestination($info['destination']);
$dateArray = explode('-', $info['date']);
$transfer->setDate(new \DateTime($dateArray[2].'-'.$dateArray[1].'-'.$dateArray[0]));
$transfer->setAddress($info['address']);
$transfer->setFlightTime($info['flightTime']);
$transfer->setPickupTime($info['pickupTime']);
$transfer->setSeats($info['seats']);
$transfer->setAirline($info['airline']);
$transfer->setFlight($info['flight']);
$transfer->setType($info['type']);
$transfer->setBags($info['bags']);
$transfer->setFare($info['fare']);
// join
$transfer->setCustomer($customer);
$em = $this->getDoctrine()->getManager();
$em->persist($transfer);
$em->flush();
}
}
private function createAndSendNewPromocode($customer)
{
$newPromocode = $this->container->get('platform.useful')->createRandomPassword();
$promocode = new Promocode();
$promocode->setValue($newPromocode);
$promocode->setType('short');
$promocode->setDiscount(10);
$em = $this->getDoctrine()->getManager();
$em->persist($promocode);
$em->flush();
$mail = $this->container->get('platform.mail');
$mail->send(
$customer->getEmail(),
'A promotional code for your next transfer on dubair.ie !',
$this->renderView('PlatformBundle:Mail:promocode.html.twig', array(
'customer' => $customer,
'promocode' => $newPromocode
)),
'info#dubair.ie'
);
}
private function stripeConfig()
{
$stripe = array(
"secret_key" => "xx",
"publishable_key" => "xx"
);
\Stripe\Stripe::setApiKey($stripe['secret_key']);
return $stripe;
}
public function stripeChargeAction(Request $req)
{
$this->stripeConfig();
$info = $req->getSession()->get('info');
$amount = ($info['fare'] * 100);
$info['payed'] = true;
$req->getSession()->set('info', $info);
$token = $req->request->get('stripeToken');
$customer = \Stripe\Customer::create(array(
'email' => $req->request->get('email'),
'card' => $token
));
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $amount,
'currency' => 'eur'
));
return new RedirectResponse('success');
}
}
thanks

Categories