Coinpayment Laravel integration. Division by zero Exception - laravel

I am trying to integrate coinpayment. By using this - https://github.com/hexters/CoinPayment
But I got error says:
exception: "ErrorException"
file: "C:\xampp\htdocs\coinpayment\vendor\hexters\coinpayment\src\Http\Controllers\CoinPaymentController.php"
line: 45
message: "Division by zero"

Please Refer to author new commits in the git repository as he updated the package https://github.com/hexters/CoinPayment/commit/cf7de99e18948fe385e75dfa8ded0fb378c33ad4
In case the link is not working then go to your app route and then to vendor folder and follow path vendor/hexters/coinpayment/src/Http/Controllers and update CoinPaymentController.php file's public function ajax_rates() function with the below given code
public function ajax_rates(Request $req, $usd){
$coins = [];
$aliases = [];
$rates = CoinPayment::api_call('rates', [
'accepted' => 1
])['result'];
$rateBtc = $rates['BTC']['rate_btc'];
$rateUsd = $rates[config('coinpayment.default_currency')]['rate_btc'];
$rateAmount = $rateUsd * $usd;
$fiat = [];
$coins_accept = [];
foreach($rates as $i => $coin){
if((FLOAT) $rates[$i]['rate_btc'] > 0) {
if((INT) $coin['is_fiat'] === 0){
$rate = ($rateAmount / $rates[$i]['rate_btc']);
$coins[] = [
'name' => $coin['name'],
'rate' => number_format($rate,8,'.',''),
'iso' => $i,
'icon' => 'https://www.coinpayments.net/images/coins/' . $i . '.png',
'selected' => $i == 'BTC' ? true : false,
'accepted' => $coin['accepted']
];
$aliases[$i] = $coin['name'];
}
if((INT) $coin['is_fiat'] === 0 && $coin['accepted'] == 1){
$rate = ($rateAmount / $rates[$i]['rate_btc']);
$coins_accept[] = [
'name' => $coin['name'],
'rate' => number_format($rate,8,'.',''),
'iso' => $i,
'icon' => 'https://www.coinpayments.net/images/coins/' . $i . '.png',
'selected' => $i == 'BTC' ? true : false,
'accepted' => $coin['accepted']
];
}
if((INT) $coin['is_fiat'] === 1){
$fiat[$i] = $coin;
}
}
}
return response()->json([
'coins' => $coins,
'coins_accept' => $coins_accept,
'aliases' => $aliases,
'fiats' =>$fiat
]);
}

Related

Laravel - How to update table multiple rows at once

I have this variable called $projectFieldOptions and it's output is like this:
https://prnt.sc/7HtxrfTy9HiI.
Now, In the Controller I need to update this. What I am doing this, first delete all the existing rows based on id_feed and id_project and then loop through this variable $projectFieldOptions and insert it. Like this:
if( $request->feed_type !== 'scrape' ) {
$delete_mapping = DB::connection($db_name)->table($db_name . '.feed_mappings')
->where('id_feed', '=', $id_feed)
->where('id_project', '=', $token)
->delete();
}
// now insert
$field_mapping = true;
if( $request->feed_type !== 'scrape' ) {
if( count($projectFieldOptions) ) {
foreach ($projectFieldOptions as $mapping) {
$data[] = [
'id_feed' => $id_feed,
'id_project' => $token,
'import_field_slug' => $mapping['value'],
'internal_field_slug' => $mapping['custom'] ? $mapping['custom_field'] : $mapping['text'],
'custom_field' => $mapping['custom'],
'updates' => $mapping['updates'],
'removes' => $mapping['removes'],
'import' => 1,
'date_add' => now(),
'date_upd' => now()
];
}
} else {
$data = [];
}
$field_mapping = DB::connection($db_name)->table($db_name . ".feed_mappings")->insert($data);
}
Now, I don't want to delete existing rows instead I want to update those rows based on the id_feed_mappings. Can you tell how can I do this?
Check if this would work, to update based on id_feed_mappings value, you can use the ->where('id_feed_mappings', '=' ,'a value or variable') before ->update($data)
if( $request->feed_type !== 'scrape' ) {
// try using update instead of insert
$field_mapping = true;
if( $request->feed_type !== 'scrape' ) {
if( count($projectFieldOptions) ) {
foreach ($projectFieldOptions as $mapping) {
$data[] = [
'id_feed' => $id_feed,
'id_project' => $token,
'import_field_slug' => $mapping['value'],
'internal_field_slug' => $mapping['custom'] ? $mapping['custom_field'] : $mapping['text'],
'custom_field' => $mapping['custom'],
'updates' => $mapping['updates'],
'removes' => $mapping['removes'],
'import' => 1,
'date_add' => now(),
'date_upd' => now()
];
}
} else {
$data = [];
}
$field_mapping = DB::connection($db_name)->table($db_name . ".feed_mappings")->update($data);
}

Laravel 1 row missing while inserting and

$purchase_line_datas = PurchaseLine::where('transaction_id',
$transaction->id)->get(); $i = 0;
$input = [];
foreach ($purchase_line_datas as $key => $purchase_line_data) {
if (!$enable_stock_transfer) {
$qty_available = $this->productUtil->num_uf($purchases[$i]['quantity']);
} else {
$qty_available = 0;
}
$item = array(
"business_id" => $business_id,
"transaction_id" => $purchase_line_data->transaction_id,
"purchase_line_id" => $purchase_line_data->id,
"variation_id" => $purchase_line_data->variation_id,
"contact_id" => $transaction_data['contact_id'],
"product_id" => $purchase_line_data->product_id,
"ref_no" => $ref_no,
"new_barcode" => $purchase_line_data->barcode,
"default_sell_price" => $this->productUtil->num_uf($purchases[$i]['default_sell_price']),
"purchase_qty" => $this->productUtil->num_uf($purchases[$i]['quantity']),
"qty_available" => $this->productUtil->num_uf($qty_available),
"created_at" => Carbon::now()
);
array_push($input, $item);
$i++;
}
ProductPurchaseSl::insert($input);
in this code I am inserting an array but after inserting.. it's showing that one row is missing.And it's happening very often.I couldn't be able to solve this problem.

because it shows Undefined offset: 0, seeder laravel?

I have the following for in which I create the records
foreach ($v as $k => $f){
if($v[$k] != false && $f['zip_code'] !=''){
$state = State::whereCode($f['code'])->get();
var_dump($state[0]->id);
\App\Models\ZipCodes::create([
'uuid' => Uuid::generate(4)->string,
'zip_code' => $f['zip_code'],
'city' => $f['city'],
'county' => $f['county'],
'state_id' => $state[0]->id,
]);
}
}
I have noticed that the error appears in the field 'state_id' => $ state [0] -> id
since if I comment and delete it from the table it doesn't give me the error.
In fact if I just leave
foreach ($v as $k => $f){
if($v[$k] != false && $f['zip_code'] !=''){
$state = State::whereCode($f['code'])->get();
var_dump($state[0]->id);
}
}
The same generates the error.

Specific ID exception laravel 5.4/5.5

I'm working on a functionality where only a user with the ID number 3 can bet if the match is 1 minute away from starting, it's a success, but now those matches that has the status "Open" is not allowed to place bets. here is the code:
public function *addMatchBet*(Request $request){
$rules = [
'matchid' => 'required|integer|exists:matches,id',
'teamid' => 'required|integer|exists:teams,id',
'bet_amount' => 'required|integer|min:100'
];
$validation = \**Validator**::make($request->all(), $rules);
if ($validation->passes()) {
$user = \**Auth**::user();
$match = \App\**Match**::find($request->matchid);
$team = \App\**Team**::find($request->teamid);
if(!in_array($team->id, [$match->team_a, $match->team_b])) {
return [
'success' => false,
'errors' => [
'bet' => ['Match teams have been updated! Please refresh
page and try again.']
]
];
}
if($match && $match->status == 'open') {
$betCount = $user->bets
->where('match_id', $request->matchid)
->count();
if($match->isClosing(0)) {
return [
'success' => false,
'errors' => [
'bet' => ['Could no longer bet. This match is now
starting!']
]
];
}
}
}
}
Any ideas anyone? TYIA
I've found a solution, this was the code:
if($match && $match->isClosing(0)) {
if($user->id == 3){
$betCount = $user->bets
->where('match_id', $request->matchid)
->count();
}
else{
return [
'success' => false,
'errors' => [
'bet' => ['Could no longer bet. This match is now starting!']
]
];
}
}

Make an error message on Magento checkout page (Shipping Method stage)

I developed a Magento shipping method module and it works fine.
I can retrieve the list of available shipping methods from my remote service but I want to have an error message if something will be wrong with connection to the srvice or etc.
The code of collectRates carrier class is listed below.
public function collectRates(Mage_Shipping_Model_Rate_Request $request) {
if (!$this->getConfigFlag('active')) {
return false;
}
require_once Mage::getBaseDir() . '/app/code/local/Citymail/CitymailDeliveryOption/lib/syvo_service_connect.php';
$citymail_service_url = $this->getConfigData('service_url') . '/syvo_service';
$connection = new syvo_service_connect($citymail_service_url);
if($connection->connect()) {
$handling = Mage::getStoreConfig('carriers/'.$this->_code.'/handling');
$rate_result = Mage::getModel('shipping/rate_result');
$product_qty = 0;
$products_data = array();
$currency = Mage::app()->getStore()->getCurrentCurrencyCode();
$quote = Mage::getSingleton('checkout/session')->getQuote();
foreach($quote->getAllVisibleItems() as $cartItem) {
$product_qty += $cartItem->getQty();
$products_data[$cartItem->getId()] = array(
'length_units' => 'cm',
'length' => 0,
'width' => 0,
'height' => 0,
'weight_units' => 'kg',
'weight' => $cartItem->getProduct()->getWeight(),
'shippable' => 'a',
'sell_price' => $cartItem->getProduct()->getPrice(),
'currency' => $currency,
);
}
$shipping_address = Mage::getModel('checkout/cart')->getQuote()->getShippingAddress();
$password = md5($this->getConfigData('service_password'));
$params = array(
'passw=' . $password,
'login=' . $this->getConfigData('service_login'),
'action=get_shipping_options',
'product_qty=' . $product_qty,
'products_data=' . json_encode($products_data),
'country=' . $shipping_address->getCountryId(),
'postal_code=' . $shipping_address->getPostcode(),
);
$response = $connection->send(implode('&', $params), 0, 30);
$response_status_line = $connection->getResponseStatusLine();
if((int)$response_status_line[1] == 403) {
//Access denied message
}
else {
$response_array = json_decode($response);
$citymail_service_points_data = array();
if($response_array->syvo_service_responce->type == 'success') {
$options = array();
foreach($response_array->syvo_service_responce->data->syvo_shipping_methods as $key_method => $shipping_method) {
$method_key = 'opt--' . $shipping_method->type . '--' . $shipping_method->distributor;
if($shipping_method->type == 'DHL_SERVICE_POINT') {
$citymail_service_points_data['service_points'][$shipping_method->id] = array(
'dhl_service_point_postcode' => $shipping_method->postcode,
'dhl_service_point_address' => $shipping_method->address,
);
$method_key .= '--' . $shipping_method->id;
}
$method = Mage::getModel("shipping/rate_result_method");
$method->setCarrier($this->_code);
$method->setCarrierTitle(Mage::getStoreConfig('carriers/' . $this->_code . '/title'));
$method->setMethod($method_key);
$method->setMethodTitle($shipping_method->text);
$method->setCost($shipping_method->rate);
$method->setPrice($shipping_method->rate + $handling);
$rate_result->append($method);
}
$street = $shipping_address->getStreet();
$citymail_temporary_order_data = array(
'login' => $this->getConfigData('service_login'),
'password' => $password,
'country_id' => $shipping_address->getCountryId(),
'company_name' => $shipping_address->getCompany(),
'name' => trim($shipping_address->getFirstname() . ' ' . $shipping_address->getLastname()),
'postal_code' => $shipping_address->getPostcode(),
'phone_number' => $shipping_address->getTelephone(),
'email' => $shipping_address->getEmail(),
'street' => $street[0],
'city' => $shipping_address->getCity(),
'matrix_id' => $response_array->syvo_service_responce->data->matrix_id,
'service_url' => $citymail_service_url,
);
$citymail_temporary_order_data = $citymail_service_points_data + $citymail_temporary_order_data;
Mage::getSingleton('core/session')->setCitymailTemporaryOrderData($citymail_temporary_order_data);
}
else {
//Some error handler
$error = Mage::getModel("shipping/rate_result_error");
$error->setCarrier('citymaildeliveryoption');
$error->setErrorMessage('sasasas');
$rate_result->append($error);
}
}
}
else {
}
return $rate_result;
}
This code has to return an error message if the module couldn't retrieve the list of shipping methods:
$error = Mage::getModel("shipping/rate_result_error");
$error->setCarrier('citymaildeliveryoption');
$error->setErrorMessage('sasasas');
$rate_result->append($error);
But the error is not displaying.
I checked an existing (core) Magento modules which use error handlers too (Ups, Usps modules) and error handlers of these modules also do not work, error message is not displaying.
Could you please advice some solution of this problem.
Tnank you!
Your code is good. You just need a little bit configuration for your carrier to always displays its methods.
Has shown in Mage_Shipping_Model_Shipping->collectCarrierRates() (line 176), Magento checks for 'showmethod' in your carrier config if a result is in error (and discard it, if it evaluates to 0) :
if ($carrier->getConfigData('showmethod') == 0 && $result->getError()) {
return $this;
}
So you just have to add this in your config.xml :
<?xml version="1.0" encoding="UTF-8"?>
<config>
<default>
<carriers>
<citymaildeliveryoption>
<showmethod>1</showmethod>
</citymaildeliveryoption>
</carriers>
</default>
</config>

Resources