Call to undefined method createMonthlySubscription() - php

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']);

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');
}
}
}

Ethereum Transfer token via smart contract

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.

update stock after order placed in laravel php

I'm using Laravel i need to do update stock after order placed from a client/user app i used Http api for that but when i added stock update code in Http api file i'm getting internal server error in user app and also order is no placing if i remove stock update code from Http api it is taking order without error and stock update and the error i'm getting live.ERROR: Undefined variable: total_stock {"userId":1,"exception":"[object] (ErrorException(code: 0): Undefined variable: total_stock at /home/ttrr/domain/folder/app/Http/Controllers/Api/V1/OrderController.php:280) [stacktrace]
Here is my stock update code
$type = $c['variation'][0]['type'];
$var_store = [];
foreach (json_decode($product['variations'], true) as $var) {
if ($type == $var['type']) {
$var['stock'] -= $c['quantity'];
}
array_push($var_store, $var);
}
Product::where(['id' => $product['id']])->update([
'variations' => json_encode($var_store),
'total_stock' => $product['total_stock'] - $c['quantity'],
]);
Here is my ordercontroll.php
class OrderController extends Controller
{
public function track_order(Request $request)
{
$validator = Validator::make($request->all(), [
'order_id' => 'required'
]);
if ($validator->fails()) {
return response()->json(['errors' => Helpers::error_processor($validator)], 403);
}
$order = Order::with(['restaurant', 'delivery_man.rating'])->withCount('details')->where(['id' => $request['order_id'], 'user_id' => $request->user()->id])->first();
if($order)
{
$order['restaurant'] = $order['restaurant']?Helpers::restaurant_data_formatting($order['restaurant']):$order['restaurant'];
$order['delivery_address'] = $order['delivery_address']?json_decode($order['delivery_address']):$order['delivery_address'];
$order['delivery_man'] = $order['delivery_man']?Helpers::deliverymen_data_formatting([$order['delivery_man']]):$order['delivery_man'];
unset($order['details']);
}
else
{
return response()->json([
'errors' => [
['code' => 'schedule_at', 'message' => trans('messages.not_found')]
]
], 404);
}
return response()->json($order, 200);
}
public function place_order(Request $request)
{
$validator = Validator::make($request->all(), [
'order_amount' => 'required',
'payment_method'=>'required|in:cash_on_delivery,digital_payment',
'order_type' => 'required|in:take_away,delivery',
'restaurant_id' => 'required',
'distance' => 'required_if:order_type,delivery',
'address' => 'required_if:order_type,delivery',
'longitude' => 'required_if:order_type,delivery',
'latitude' => 'required_if:order_type,delivery',
]);
if ($validator->fails()) {
return response()->json(['errors' => Helpers::error_processor($validator)], 403);
}
$coupon = null;
$delivery_charge = null;
$schedule_at = $request->schedule_at?\Carbon\Carbon::parse($request->schedule_at):now();
if($request->schedule_at && $schedule_at < now())
{
return response()->json([
'errors' => [
['code' => 'order_time', 'message' => trans('messages.you_can_not_schedule_a_order_in_past')]
]
], 406);
}
$restaurant = Restaurant::with('discount')->whereTime('opening_time','<=',$schedule_at->format('H:i'))->whereTime('closeing_time','>=',$schedule_at->format('H:i'))->where('id', $request->restaurant_id)->first();
if(!$restaurant)
{
return response()->json([
'errors' => [
['code' => 'order_time', 'message' => trans('messages.restaurant_is_closed_at_order_time')]
]
], 406);
}
if($request->schedule_at && !$restaurant->schedule_order)
{
return response()->json([
'errors' => [
['code' => 'schedule_at', 'message' => trans('messages.schedule_order_not_available')]
]
], 406);
}
if ($request['coupon_code']) {
$coupon = Coupon::active()->where(['code' => $request['coupon_code']])->first();
if (isset($coupon)) {
$staus = CouponLogic::is_valide($coupon, $request->user()->id ,$request['restaurant_id']);
if($staus==407)
{
return response()->json([
'errors' => [
['code' => 'coupon', 'message' => trans('messages.coupon_expire')]
]
], 407);
}
else if($staus==406)
{
return response()->json([
'errors' => [
['code' => 'coupon', 'message' => trans('messages.coupon_usage_limit_over')]
]
], 406);
}
else if($staus==404)
{
return response()->json([
'errors' => [
['code' => 'coupon', 'message' => trans('messages.not_found')]
]
], 404);
}
if($coupon->coupon_type == 'free_delivery')
{
$delivery_charge = 0;
$coupon = null;
}
} else {
return response()->json([
'errors' => [
['code' => 'coupon', 'message' => 'not found!']
]
], 401);
}
}
$per_km_shipping_charge = (float)BusinessSetting::where(['key' => 'per_km_shipping_charge'])->first()->value;
$minimum_shipping_charge = (float)BusinessSetting::where(['key' => 'minimum_shipping_charge'])->first()->value;
$original_delivery_charge = ($request->distance * $per_km_shipping_charge > $minimum_shipping_charge) ? $request->distance * $per_km_shipping_charge : $minimum_shipping_charge;
if($request['order_type'] != 'take_away' && !$restaurant->free_delivery && $delivery_charge == null)
{
$delivery_charge = ($request->distance * $per_km_shipping_charge > $minimum_shipping_charge) ? $request->distance * $per_km_shipping_charge : $minimum_shipping_charge;
}
if($request->latitude && $request->longitude)
{
$point = new Point($request->latitude,$request->longitude);
$zone = Zone::where('id', $restaurant->zone_id)->contains('coordinates', $point)->first();
if(!$zone)
{
$errors = [];
array_push($errors, ['code' => 'coordinates', 'message' => trans('messages.out_of_coverage')]);
return response()->json([
'errors' => $errors
], 403);
}
}
$address = [
'contact_person_name' => $request->contact_person_name?$request->contact_person_name:$request->user()->f_name.' '.$request->user()->f_name,
'contact_person_number' => $request->contact_person_number?$request->contact_person_number:$request->user()->phone,
'address_type' => $request->address_type?$request->address_type:'Delivery',
'address' => $request->address,
'longitude' => (string)$request->longitude,
'latitude' => (string)$request->latitude,
];
$total_addon_price = 0;
$product_price = 0;
$restaurant_discount_amount = 0;
$order_details = [];
$order = new Order();
$order->id = 100000 + Order::all()->count() + 1;
$order->user_id = $request->user()->id;
$order->order_amount = $request['order_amount'];
$order->payment_status = 'unpaid';
$order->order_status = $request['payment_method']=='digital_payment'?'failed':'pending';
$order->coupon_code = $request['coupon_code'];
$order->payment_method = $request->payment_method;
$order->transaction_reference = null;
$order->order_note = $request['order_note'];
$order->order_type = $request['order_type'];
$order->restaurant_id = $request['restaurant_id'];
$order->delivery_charge = $delivery_charge??0;
$order->original_delivery_charge = $original_delivery_charge;
$order->delivery_address = json_encode($address);
$order->schedule_at = $schedule_at;
$order->scheduled = $request->schedule_at?1:0;
$order->otp = rand(1000, 9999);
$order->pending = now();
$order->created_at = now();
$order->updated_at = now();
foreach ($request['cart'] as $c) {
/*foreach (json_decode($product['variations'], true) as $var) {
if ($type == $var['type'] && $var['stock'] < $c['quantity']) {
$validator->getMessageBag()->add('stock', 'Stock is insufficient! available stock ' . $var['stock']);
}
}*/
if ($c['item_campaign_id'] != null) {
$product = ItemCampaign::find($c['item_campaign_id']);
if ($product) {
$type = $c['variation'][0]['type'];
foreach (json_decode($product['variations'], true) as $var) {
if ($type == $var['type'] && $var['stock'] < $c['quantity']) {
$validator->getMessageBag()->add('stock', 'Stock is insufficient! available stock ' . $var['stock']);
}
else {
$price = $product['price'];
}
}
/*if (count(json_decode($product['variations'], true)) > 0) {
$price = Helpers::variation_price($product, json_encode($c['variation']));
}*/
$product->tax = $restaurant->tax;
$product = Helpers::product_data_formatting($product);
$addon_data = Helpers::calculate_addon_price(\App\Models\AddOn::whereIn('id',$c['add_on_ids'])->get(), $c['add_on_qtys']);
$or_d = [
'food_id' => null,
'item_campaign_id' => $c['item_campaign_id'],
'food_details' => json_encode($product),
'quantity' => $c['quantity'],
'price' => $price,
'tax_amount' => Helpers::tax_calculate($product, $price),
'discount_on_food' => Helpers::product_discount_calculate($product, $price, $restaurant),
'discount_type' => 'discount_on_product',
'variant' => json_encode($c['variant']),
'is_stock_decreased' => 1,
'variation' => json_encode($c['variation']),
'add_ons' => json_encode($addon_data['addons']),
'total_add_on_price' => $addon_data['total_add_on_price'],
'created_at' => now(),
'updated_at' => now()
];
$order_details[] = $or_d;
$total_addon_price += $or_d['total_add_on_price'];
$product_price += $price*$or_d['quantity'];
$restaurant_discount_amount += $or_d['discount_on_food']*$or_d['quantity'];
} else {
return response()->json([
'errors' => [
['code' => 'campaign', 'message' => 'not found!']
]
], 401);
}
} else {
$product = Food::find($c['food_id']);
if ($product) {
if (count(json_decode($product['variations'], true)) > 0) {
$price = Helpers::variation_price($product, json_encode($c['variation']));
} else {
$price = $product['price'];
}
$product->tax = $restaurant->tax;
$product = Helpers::product_data_formatting($product);
$addon_data = Helpers::calculate_addon_price(\App\Models\AddOn::whereIn('id',$c['add_on_ids'])->get(), $c['add_on_qtys']);
$or_d = [
'food_id' => $c['food_id'],
'item_campaign_id' => null,
'food_details' => json_encode($product),
'quantity' => $c['quantity'],
'price' => $price,
'is_stock_decreased' => 1,
'tax_amount' => Helpers::tax_calculate($product, $price),
'discount_on_food' => Helpers::product_discount_calculate($product, $price, $restaurant),
'discount_type' => 'discount_on_product',
'variant' => json_encode($c['variant']),
'variation' => json_encode($c['variation']),
'add_ons' => json_encode($addon_data['addons']),
'total_add_on_price' => $addon_data['total_add_on_price'],
'created_at' => now(),
'updated_at' => now()
];
//stock update code
$type = $c['variation'][0]['type'];
$var_store = [];
foreach (json_decode($product['variations'], true) as $var) {
if ($type == $var['type']) {
$var['stock'] -= $c['quantity'];
}
array_push($var_store, $var);
}
Product::where(['id' => $product['id']])->update([
'variations' => json_encode($var_store),
'total_stock' => $product['total_stock'] - $c['quantity'],
]);
DB::table('order_details')->insert($or_d);
$total_addon_price += $or_d['total_add_on_price'];
$product_price += $price*$or_d['quantity'];
$restaurant_discount_amount += $or_d['discount_on_food']*$or_d['quantity'];
$order_details[] = $or_d;
} else {
return response()->json([
'errors' => [
['code' => 'food', 'message' => 'not found!']
]
], 401);
}
}
And tried mentioning variable like this 'total_stock' =>$total_stock but still not working

How to send the Paypal transactions and order to the database after the payment , Laravel 8

I'm using srmklive Paypal v1, and when the payment is successful how I cam transfer the customer's billing to the database, is it related to the paypalcontroller of maybe javascript (ajax)?
This is my PaypalController:
<?php
namespace App\Http\Controllers;
use App\Invoice;
use App\Item;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Srmklive\PayPal\Services\AdaptivePayments;
use Srmklive\PayPal\Services\ExpressCheckout;
class PayPalController extends Controller
{
/**
* #var ExpressCheckout
*/
protected $provider;
public function __construct()
{
$this->provider = new ExpressCheckout();
}
public function getIndex(Request $request)
{
$response = [];
if (session()->has('code')) {
$response['code'] = session()->get('code');
session()->forget('code');
}
if (session()->has('message')) {
$response['message'] = session()->get('message');
session()->forget('message');
}
return view('welcome', compact('response'));
}
/**
* #param \Illuminate\Http\Request $request
*
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
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!"]);
}
}
/**
* Process payment on PayPal.
*
* #param \Illuminate\Http\Request $request
*
* #return \Illuminate\Http\RedirectResponse
*/
public function getExpressCheckoutSuccess(Request $request)
{
$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'], 9.99, $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);
$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!"]);
} 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);
}
/**
* Parse PayPal IPN.
*
* #param \Illuminate\Http\Request $request
*/
public function notify(Request $request)
{
if (!($this->provider instanceof ExpressCheckout)) {
$this->provider = new ExpressCheckout();
}
$request->merge(['cmd' => '_notify-validate']);
$post = $request->all();
$response = (string) $this->provider->verifyIPN($post);
$logFile = 'ipn_log_'.Carbon::now()->format('Ymd_His').'.txt';
Storage::disk('local')->put($logFile, $response);
}
/**
* Set cart data for processing payment on PayPal.
*
* #param bool $recurring
*
* #return array
*/
protected function getCheckoutData($recurring = false)
{
$data = [];
$order_id = Invoice::all()->count() + 1;
if ($recurring === true) {
$data['items'] = [
[
'name' => 'Monthly Subscription '.config('paypal.invoice_prefix').' #'.$order_id,
'price' => 0,
'qty' => 1,
],
];
$data['return_url'] = url('/paypal/ec-checkout-success?mode=recurring');
$data['subscription_desc'] = 'Monthly Subscription '.config('paypal.invoice_prefix').' #'.$order_id;
} else {
$data['items'] = [
[
'name' => 'Product 1',
'price' => 9.99,
'qty' => 1,
],
[
'name' => 'Product 2',
'price' => 4.99,
'qty' => 2,
],
];
$data['return_url'] = url('/paypal/ec-checkout-success');
}
$data['invoice_id'] = config('paypal.invoice_prefix').'_'.$order_id;
$data['invoice_description'] = "Order #$order_id Invoice";
$data['cancel_url'] = url('/');
$total = 0;
foreach ($data['items'] as $item) {
$total += $item['price'] * $item['qty'];
}
$data['total'] = $total;
return $data;
}
/**
* Create invoice.
*
* #param array $cart
* #param string $status
*
* #return \App\Invoice
*/
protected function createInvoice($cart, $status)
{
$invoice = new Invoice();
$invoice->title = $cart['invoice_description'];
$invoice->price = $cart['total'];
if (!strcasecmp($status, 'Completed') || !strcasecmp($status, 'Processed')) {
$invoice->paid = 1;
} else {
$invoice->paid = 0;
}
$invoice->save();
collect($cart['items'])->each(function ($product) use ($invoice) {
$item = new Item();
$item->invoice_id = $invoice->id;
$item->item_name = $product['name'];
$item->item_price = $product['price'];
$item->item_qty = $product['qty'];
$item->save();
});
return $invoice;
}
public function cancel()
{
dd('Your payment is canceled. You can create cancel page here.');
}
/**
* Responds with a welcome message with instructions
*
* #return \Illuminate\Http\Response
*/
public function success(Request $request)
{
$provider = new ExpressCheckout;
$response = $provider->getExpressCheckoutDetails($request->token);
if (in_array(strtoupper($response['ACK']), ['SUCCESS', 'SUCCESSWITHWARNING'])) {
dd('Your payment was successfully. You can create success page here.');
}
dd('Something is wrong.');
}
}
The table whose I want to transfer the billing called "customer_details" , any idea how to make that, please?

I have added the tables in phpmyadmin but it is not working

So I have a source code of this website. At first it did not work so I made a new table called users then added the username, password etc after that the error has been removed when I register but when I try to login it does not work and when I go to phpmyadmin there is no new entry please look at source code and etc
namespace rbxWorkshop
{
use \EasyRequest as Client;
use \DiscordWebhooks\Embed;
use \SecurityLib as SecurityLib;
use \PHPMailer\PHPMailer\PHPMailer;
use \RandomLib\Factory as RandomLib;
use \DiscordWebhooks\Client as DiscordClient;
class System
{
private $errorReporting = false;
private $maintenanceMode = false;
private $allowRegistrations = true;
// Quick Checks
public function loggedIn()
{
if ($_SESSION['username'] == "") {
return false;
} else {
$this->isBanned($_SESSION['username']);
return true;
}
}
public function varChecks()
{
if ($this->errorReporting === TRUE) {
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
} else {
error_reporting(0);
}
if ($this->maintenanceMode === TRUE) {
header("Location: /maintenance.php");
}
}
public function prepare($param)
{
return mysqli_real_escape_string($this->database(), $param);
}
public function userAgent()
{
return "rbxWorkshop/1.1; +https://overwardnetwork.net";
}
public function isBanned($username)
{
$sql = "SELECT * FROM `users` WHERE `username`='$username'";
$array = mysqli_fetch_array($this->database()->query($sql));
if ($array['banned'] == 1) {
unset($_COOKIE['RWS_Session_ID']);
unset($_SESSION['username']);
session_destroy();
return true;
} else {
return false;
}
}
// Database
public function database()
{
define("DB_HOST", "localhost");
define("DB_USER", "overward_root");
define("DB_PASS", "andrieX321");
define("DB_NAME", "overward_Cookie");
$connection = new \mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($connection->connect_errno) {
exit("Failed to connect: " . $connection->connect_error);
}
return $connection;
}
public function mailUser($username, $service)
{
if ($this->userExists($username)) {
if ($service == "verify") {
$email = file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/emails/email_1.min.html");
$sql = "SELECT * FROM `users` WHERE `username`='$username'";
$array = mysqli_fetch_array($this->database()->query($sql));
$email = str_replace("%username%", $username, $email);
$email = str_replace("%code%", $array['activation_code'], $email);
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.mailgun.org';
$mail->SMTPAuth = true;
$mail->Username = 'postmaster#mail.rbxworkshop.net';
$mail->Password = 'f030a7e3cd1310e5e7525c287cdac4cd';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('verification#rbxworkshop.net', 'rbxWorkshop');
$mail->addAddress("{$array['email_address']}", "{$array['username']}");
$mail->isHTML(true);
$mail->Subject = 'rbxWorkshop Verification';
$mail->Body = "{$email}";
if (!$mail->send()) {
$json = array(
'status' => "error",
'reason' => "{$mail->ErrorInfo}",
);
return json_encode($json);
} else {
$json = array(
'status' => "success",
'email' => "{$array['email_address']}"
);
return json_encode($json);
}
} elseif ($service == "recover") {
} else {
$json = array(
'status' => "error",
'reason' => "Service parameter is unknown"
);
return json_encode($json);
}
} else {
$json = array(
'status' => "error",
'reason' => "User not found"
);
return json_encode($json);
}
}
public function loginUser($username, $password)
{
$Security = new Security();
$sessionID = $Security->rwsCookie();
if ($this->userExists($username)) {
$sql = "SELECT * FROM `users` WHERE `username`='$username'";
$array = mysqli_fetch_array($this->database()->query($sql));
if ($array['active'] == "0") {
$json = array(
'status' => "error",
'reason' => "Account is not activated"
);
return json_encode($json);
} elseif (password_verify($password, $array['password'])) {
$json = array(
'status' => "success",
'username' => "{$username}"
);
$_SESSION['username'] = $username;
$expiryDate = new \DateTime("+1 week");
setcookie("RWS_Session_ID", "{$sessionID}", "{$expiryDate->getTimestamp()}", "/", "rbxworkshop.net", true, false);
return json_encode($json);
} elseif (!password_verify($password, $array['password'])) {
$json = array(
'status' => "error",
'reason' => "Password is incorrect"
);
return json_encode($json);
} else {
$json = array(
'status' => "error",
'reason' => "Unknown error"
);
return json_encode($json);
}
} else {
$json = array(
'status' => "error",
'reason' => "User not found"
);
return json_encode($json);
}
}
public function registerUser($username, $password, $email_address, $ip_address)
{
if ($this->allowRegistrations) {
$Security = new Security();
$discord_code = $Security->lowStr();
$activation_code = $Security->lowStr();
$encrypted_password = password_hash($password, PASSWORD_DEFAULT, ['cost' => '12']);
$sql = "INSERT INTO `users` (username, password, email_address, ip_address, activation_code, discord_code)
VALUES ('$username', '$encrypted_password', '$email_address', '$ip_address', '$activation_code', '$discord_code')";
$sql_ip = "SELECT * FROM `users` WHERE `ip_address`='$ip_address'";
$sql_email = "SELECT * FROM `users` WHERE `email_address`='$email_address'";
if ($this->userExists($username)) {
$json = array(
'status' => "error",
'reason' => "Username is already in use"
);
return json_encode($json);
} elseif (mysqli_num_rows($this->database()->query($sql_ip)) == 1) {
$json = array(
'status' => "error",
'reason' => "IP address is already in use"
);
return json_encode($json);
} elseif (mysqli_num_rows($this->database()->query($sql_email)) == 1) {
$json = array(
'status' => "error",
'reason' => "Email address is already in use"
);
return json_encode($json);
} else {
$this->database()->query($sql);
$this->mailUser("{$username}", "verify");
$json = array(
'status' => "success",
'username' => "{$username}"
);
return json_encode($json);
}
} else {
$json = array(
'status' => "error",
'reason' => "Registrations are closed"
);
return json_encode($json);
}
}
public function userExists($username)
{
$sql = "SELECT * FROM `users` WHERE `username`='$username'";
if (mysqli_num_rows($this->database()->query($sql)) == 1) {
return true;
} else {
return false;
}
}
public function banUser($type, $username, $discord_id)
{
if ($type == "discord") {
$sql = "SELECT * FROM `users` WHERE `discord_id`='$discord_id'";
if (mysqli_num_rows($this->database()->query($sql))) {
$sql = "UPDATE `users` SET `banned`=1 WHERE `discord_id`='$discord_id'";
$this->database()->query($sql);
$json = array(
'status' => "success",
'discord_id' => "{$discord_id}"
);
return json_encode($json);
} else {
$json = array(
'status' => "error",
'reason' => "User not found"
);
return json_encode($json);
}
} elseif ($type == "website") {
$sql = "SELECT * FROM `users` WHERE `username`='$username'";
if (mysqli_num_rows($this->database()->query($sql))) {
$sql = "UPDATE `users` SET `banned`=1 WHERE `username`='$username'";
$this->database()->query($sql);
$json = array(
'status' => "success",
'username' => "{$username}"
);
return json_encode($json);
} else {
$json = array(
'status' => "error",
'reason' => "User not found"
);
return json_encode($json);
}
} else {
$json = array(
'status' => "error",
'reason' => "Type parameter is unknown"
);
return json_encode($json);
}
}
// Discord
public function discordVerified($type, $username, $discord_id)
{
if ($type == "discord") {
$sql = "SELECT * FROM `users` WHERE `discord_id`='$discord_id'";
if (mysqli_num_rows($this->database()->query($sql)) == 1) {
$array = mysqli_fetch_array($this->database()->query($sql));
$json = array(
'status' => "success",
'username' => "{$array['username']}"
);
return json_encode($json);
} else {
$json = array(
'status' => "error",
'reason' => "Discord ID was not found"
);
return json_encode($json);
}
} elseif ($type == "website") {
$sql = "SELECT * FROM `users` WHERE `username`='$username'";
$array = mysqli_fetch_array($this->database()->query($sql));
if ($array['discord_id'] == null || "") {
return false;
} else {
return true;
}
} else {
$json = array(
'status' => "error",
'username' => "Discord ID was not found"
);
return json_encode($json);
}
}
public function verifyDiscord($discord_id, $discord_code)
{
$sql = "SELECT * FROM `users` WHERE `discord_code`='$discord_code'";
if (mysqli_num_rows($this->database()->query($sql)) == 1) {
$sql = "UPDATE `users` SET `discord_id`='$discord_id' WHERE `discord_code`='$discord_code'";
$this->database()->query($sql);
$json = array(
'status' => "success",
'discord_id' => "{$discord_id}",
);
return json_encode($json);
} else {
$json = array(
'status' => "error",
'reason' => "Discord Code was not found",
);
return json_encode($json);
}
}
public function userWebhook($username, $service)
{
$sql = "SELECT * FROM `webhooks` WHERE `username`='$username' AND `service`='$service'";
if (mysqli_num_rows($this->database()->query($sql)) == 1) {
$array = mysqli_fetch_array($this->database()->query($sql));
$json = array(
'status' => "success",
'username' => "{$array['username']}",
'webhook' => "{$array['webhook']}"
);
return json_encode($json);
} else {
$json = array(
'status' => "error",
'reason' => "User not found",
);
return json_encode($json);
}
}
public function webhookAnnouncement($service, $message)
{
$sql = "SELECT `username`, `webhook` FROM `webhooks` WHERE `service`='$service'";
while ($array = mysqli_fetch_assoc($this->database()->query($sql))) {
$Client = new DiscordClient("{$array['webhook']}");
$Embed = new Embed();
$Embed->title("rbxWorkshop Global Announcement", "https://rbxworkshop.net/");
$Embed->description("An announcement has appeared?!");
$Embed->field("Announcement", "Hey {$array['username']}! {$message}");
$Embed->image("https://rbxworkshop.net/logo.png");
$Embed->color(1738495);
$Embed->footer("rbxWorkshop");
$Client->username('rbxWorkshop')->embed($Embed)->send();
}
}
// License & Service Key
public function isBuyer($type, $username, $license)
{
if ($type == "license") {
$sql = "SELECT * FROM `licenses` WHERE `license`='$license'";
if (mysqli_num_rows($this->database()->query($sql)) == 1) {
$array = mysqli_fetch_array($this->database()->query($sql));
$json = array(
'status' => "success",
'username' => "{$array['username']}",
'license' => "{$array['license']}",
);
return json_encode($json);
} else {
$json = array(
'status' => "error",
'reason' => "License key was not found.",
);
return json_encode($json);
}
} elseif ($type == "website") {
$sql = "SELECT * FROM `licenses` WHERE `username`='$username'";
if (mysqli_num_rows($this->database()->query($sql)) == 1) {
return true;
} else {
return false;
}
} else {
$json = array(
'status' => "error",
'reason' => "Type parameter is unknown",
);
return json_encode($json);
}
}
public function licenseUser($type, $username, $discord_id)
{
if ($type == "discord") {
$Security = new Security();
$license = $Security->licenseStr();
$sql = "SELECT * FROM `users` WHERE `discord_id`='$discord_id'";
if (mysqli_num_rows($this->database()->query($sql)) == 1) {
$array = mysqli_fetch_array($this->database()->query($sql));
$username = $array['username'];
if ($this->isBuyer("website", "{$username}", "")) {
$json = array(
'status' => "error",
'reason' => "{$username} is already licensed"
);
return json_encode($json);
} else {
$extension = $Security->serviceStr();
$mgui = $Security->serviceStr();
$stub = $Security->serviceStr();
$sql_1 = "INSERT INTO `licenses` (username, license) VALUES ('$username', '$license')";
$sql_2 = "INSERT INTO `service_keys` (username, service, service_key) VALUES ('$username', 'extension', '$extension')";
$sql_3 = "INSERT INTO `service_keys` (username, service, service_key) VALUES ('$username', 'mgui', '$mgui')";
$sql_4 = "INSERT INTO `service_keys` (username, service, service_key) VALUES ('$username', 'stub', '$stub')";
$this->database()->query($sql_1);
$this->database()->query($sql_2);
$this->database()->query($sql_3);
$this->database()->query($sql_4);
$json = array(
'status' => "success",
'username' => "{$username}",
'license' => "{$license}",
);
return json_encode($json);
}
} else {
$json = array(
'status' => "error",
'reason' => "Discord ID was not found"
);
return json_encode($json);
}
} elseif ($type == "website") {
$Security = new Security();
$license = $Security->licenseStr();
$sql = "SELECT * FROM `users` WHERE `username`='$username'";
$expiry = date("Y-m-d", strtotime(date("Y-m-d", strtotime(date("F j, Y \a\t g:ia"))) . " + 30 day"));
if (mysqli_num_rows($this->database()->query($sql)) == 1) {
$array = mysqli_fetch_array($this->database()->query($sql));
$username = $array['username'];
if ($this->isBuyer("website", "{$username}", "")) {
$json = array(
'status' => "error",
'reason' => "{$username} is already licensed"
);
return json_encode($json);
} else {
$sql = "INSERT INTO `licenses` (username, license, expiry) VALUES ('$username', '$license', '$expiry')";
$this->database()->query($sql);
$json = array(
'status' => "success",
'username' => "{$username}",
'license' => "{$license}"
);
return json_encode($json);
}
} else {
$json = array(
'status' => "error",
'reason' => "User was not found"
);
return json_encode($json);
}
} else {
$json = array(
'status' => "error",
'reason' => "Type parameter is unknown"
);
return json_encode($json);
}
}
public function serviceKey($service, $username)
{
$sql = "SELECT * FROM `service_keys` WHERE `service`='$service' AND `username`='$username'";
if ($this->database()->query($sql)) {
$array = mysqli_fetch_array($this->database()->query($sql));
$json = array(
'status' => "success",
'key' => "{$array['service_key']}"
);
return json_encode($json);
} else {
$json = array(
'status' => "error",
'reason' => "Unknown error"
);
return json_encode($json);
}
}
// Other
public function randomKey()
{
$keys = file("http://rbxworkshop.net/lib/keys.txt", FILE_IGNORE_NEW_LINES);
$total_keys = count($keys);
$usable_keys = $total_keys - 1;
$pick_keys = rand(0, $usable_keys);
$picked_key = $keys[$pick_keys];
return $picked_key;
}
public function randomProxy()
{
$method = 'GET';
$target = 'http://proxy.blazingseollc.com/endpoint/list.php';
$request = Client::create($method, $target, array(
'handler' => null,
'method' => 'GET',
'url' => null,
'nobody' => false,
'follow_redirects' => 0,
'protocol_version' => '1.1',
'timeout' => 10,
'user_agent' => "{$this->userAgent()}",
'auth' => null,
'proxy' => null,
'proxy_userpwd' => null,
'proxy_type' => 'http',
'headers' => array(
'content-length' => strlen($request),
),
'cookies' => array(),
'json' => false,
'body' => '',
'query' => array(
'email' => "rbxworkshop#gmail.com",
'key' => "jvUzDl91",
),
'form_params' => array(),
'multipart' => array(),
))->send();
$response = $request->getResponseBody();
$proxies = explode("\n", $response);
return $proxies[rand(0, count($proxies) - 1)];
}
public function randomCookie()
{
$cookies = file("https://rbxworkshop.net/logs/cookie_log.txt", FILE_IGNORE_NEW_LINES);
$total_cookies = count($cookies);
$usable_cookies = $total_cookies - 1;
$pick_cookie = rand(0, $usable_cookies);
$picked_cookie = $cookies[$pick_cookie];
return $picked_cookie;
}
// Messages
public function dangerMsg($message)
{
return "<div class=\"alert alert-danger\" role=\"alert\" style='width: 85%; margin: auto; margin-top: 1%;'><b>Oh snap!</b> {$message}</div>";
}
public function successMsg($message)
{
return "<div class=\"alert alert-success\" role=\"alert\" style='width: 85%; margin: auto; margin-top: 1%;'><b>Perfect!</b> {$message}</div>";
}
public function warningMsg($message)
{
return "<div class=\"alert alert-warning\" role=\"alert\" style='width: 85%; margin: auto; margin-top: 1%;'><b>Ehh!</b> {$message}</div>";
}
public function infoMsg($message)
{
return "<div class=\"alert alert-info\" role=\"alert\" style='width: 85%; margin: auto; margin-top: 1%;'>{$message}</div>";
}
}
class Security
{
public function lowStr()
{
$factory = new RandomLib;
$generator = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::LOW));
return $generator->generateString(15, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
}
public function medStr()
{
$factory = new RandomLib;
$generator = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::MEDIUM));
return $generator->generateString(30, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
}
public function rwsCookie()
{
$factory = new RandomLib;
$generator = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::MEDIUM));
return $generator->generateString(150, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
}
public function serviceStr()
{
$factory = new RandomLib;
$generator = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::LOW));
return $generator->generateString(6, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
}
public function licenseStr()
{
$factory = new RandomLib;
$generator = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::MEDIUM));
$gen_1 = $generator->generateString(6, "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
$gen_2 = $generator->generateString(6, "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
$gen_3 = $generator->generateString(6, "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
return $gen_1 . "-" . $gen_2 . "-" . $gen_3;
}
public function str2Dec($string)
{
for ($i = 0, $j = strlen($string); $i < $j; $i++) {
$dec_array[] = ord($string{$i});
}
return $dec_array;
}
}
}

Categories