I wrote this piece of script to get the conversion rates from Yahoo API . What it does is I have a config file which has currency details I have to make an array of rates of all the currency present in the config here is my script .
Please review it and let me know if there is a better way to do this .
$cur = $this->parent->parent->config->conversionCurrencies;
//$cur=array(11=>'USD/CRC');
foreach($cur as $key=>$val){
$get_cur = str_replace("/","",$val);echo "<br>";
$code=file_get_contents('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22'.$get_cur.'%22)&format=json&env=store://datatables.org/alltableswithkeys&callback=');
var_dump($array1 = json_decode($code, true));
$rates_array = array();
$myaskRate = $array1['query']['results']['rate']['Ask'];
$mybidRate = $array1['query']['results']['rate']['Bid'];
$rates_array[$key] = round(($myaskRate+$mybidRate)/2,2);
}
var_dump( $rates_array);
Related
I want to convert from dollars to Colombian pesos in PHP and that this is saved in a variable to use it in the paypal api, i have investigated and tested and I used this page https://free.currencyconverterapi.com/
Here's my code example:
<?php
function convertCurrency($amount, $from_currency, $to_currency)
{
$apikey = '*******';
$from_Currency = urlencode($from_currency);
$to_Currency = urlencode($to_currency);
$query = "{$from_Currency}_{$to_Currency}";
// URL para solicitar los datos
$json = file_get_contents("https://free.currconv.com/api/v7/convert?q={$query}&compact=ultra&apiKey={$apikey}");
$obj = json_decode($json, true);
$val = floatval($obj["$query"]);
$totalc = $val * $amount;
return number_format($totalc, 0, '', '');
}
//uncomment to test
echo "1 USD equivale a ";
echo convertCurrency(1, 'USD', 'COP');
echo " COP";
?>
but for some reason that i don't understand, the next day the server went down or something and now i have to use something else
Researching i also learned that google has an api but so many blogs that i have read it is not clear to me how to implement it, can someone please help me?
(I know that there are questions before this one with the same topic, but I feel that they are outdated...)
I am trying to validate apple identityToken using API. I am using the firebase/php-jwt library.
I have done the below code.
$access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$auth_keys = file_get_contents('https://appleid.apple.com/auth/keys');
$public_keys = JWK::parseKeySet(json_decode($auth_keys, true));
$keys = array_keys($public_keys);
$decoded = JWT::decode($access_token, $public_keys[$keys[0]], ['RS256']);
$decoded_array = (array) $decoded;
echo '<pre>' . print_r($decoded_array, true) . '</pre>';
When I run the code the first time it works successfully. but the second time it returns 'Signature verification failed'. so i just changed from $public_keys[$keys[0]] to $public_keys[$keys[1]] so it works. but if I am trying to login again it is not working.
There is any problem with the key selection? I don't know how to select it. I tried lots of searches but I didn't found any proper solution so I hope to get help from here.
Thank you in advance
$access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
list($headb64, $bodyb64, $cryptob64) = explode('.', $access_token);
$header = JWT::jsonDecode(JWT::urlsafeB64Decode($headb64));
$kid = $header->kid;
So, I have a form that allows users to upload an excel sheet and then the system will import that excel data into mySQL.
However, every time I submit the form using AJAX, it starts the process, saves about half of the data, and then gives me a 504 gateway error. I have already changed the PHP config timeout to 300 but it still gives in half way through. I do not think that an excel sheet with a little under 1000 rows should be taking 5+ minutes?
Here is my code:
public function postImportGroup(Request $request)
{
if($request->hasFile('import_numbers')) {
$file = $request->file('import_numbers');
$file_extension = Input::file('import_numbers')->getClientOriginalExtension();
$supportedExt = array('csv', 'xls', 'xlsx');
if (!in_array_r($file_extension, $supportedExt)) {
return response()->json([
'status' => 'error',
'msg' => 'Please make sure that the uploaded file is a valid CSV, XLS, XLSX sheet.',
]);
}
}
$results = Excel::load($file)->get();
$results = json_decode($results[0], true);
$class = new DailyGroup();
$class->title = $request->group_name;
$class->user_id = Auth::guard('client')->user()->id;
$class->entries = count($results);
$class->save();
foreach ($results as $r => $value) {
//$data = array_values($value);
//return $value["employee_number"];
$group = new DailyGroupLocations();
$address = $value["address"] . ',' . $value["city"] . ',' . $value["state"] . ',' . $value["zip"];
$c = $value["country"];
$file_contents = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address) . '&components=country:' . urlencode($c) .'&sensor=false&key=xxx');
$json_decode = json_decode($file_contents);
if (isset($json_decode->results[0])) {
$group->lat = $json_decode->results[0]->geometry->location->lat;
$group->lng = $json_decode->results[0]->geometry->location->lng;
}
$phone = preg_replace('/\D+/', '', $value["ph"]);
$phone = '1'.$phone;
$group->user_id = Auth::guard('client')->user()->id;
$group->group_id = $class->id;
$group->employee_number = $value["employee_number"];
$group->work_date = $value["work_date"]["date"];
$group->first_name = $value["name"];
$group->last_name = $value["lastname"];
$group->phone = $phone;
$group->email = $value["email"];
$group->job_number = $value["job_number"];
$group->address = $value["address"];
$group->city = $value["city"];
$group->state = $value["state"];
$group->zip = $value["zip"];
$group->country = $value["country"];
$group->job_name = $value["job_name"];
$group->location = $value["location"];
$group->shift_description = $value["shift_description"];
$group->shift_start = $value["shift_start_time"];
$group->shift_end = $value["shift_end_time"];
$group->post_hours = $value["post_hours"];
$group->save();
}
return response()->json([
'status' => 'success',
'msg' => 'All data uploaded successfully. Please wait for tables to refresh.',
//'url' => '/user/location/location-areas'
]);
}
Is there anything I can do to optimize this? Am I running to many things in the foreach statement? Any tips or tricks I can use?
its Not the excel file taking its time... its the google geocode call which is blocking your code from executing.
you can get yourself an google api key to speed up your process.
reference: https://developers.google.com/maps/documentation/javascript/get-api-key
you should also Check for the response status of your geocode calls
$status = json_decode->results[0]->status;
possible status values:
OK
ZERO_RESULTS
OVER_QUERY_LIMIT
INVALID_REQUEST
UNKNOWN_ERROR
if its possible in your case you could consider pre-geocoding your dataset, store the lat and lng values with the address so you do Not have to geocode on the fly if you expect or need a fast execution.
I try to sign test bitcoin-cash transaction, and then broadcast.
For bitwasp version 0.0.35.0, the code is:
$utxoOwnerPrivateKey = 'MyPrIvAtEKey';//public key is "16Dbmp13CqdLVwjXrd6amF48t7L8gYSGBj", note - the real private key is another
$utxo = '5e44cdab9cb4a4f1871f2137ab568bf9ef2760e52816971fbaf0198f19e28378';
$utxoAmount = 598558;
$reciverPublicKey = '1EjCxux1FcohsBNGzY9KdF59Dz7MYHQyPN';
$fee = 1000;
$addressCreator = new \Btccom\BitcoinCash\Address\AddressCreator();
$networkObject = \Btccom\BitcoinCash\Network\NetworkFactory::bitcoinCash();
$keyPairInput = \BitWasp\Bitcoin\Key\PrivateKeyFactory::fromWif($utxoOwnerPrivateKey, null, $networkObject);
$outpoint = new \BitWasp\Bitcoin\Transaction\OutPoint(\BitWasp\Buffertools\Buffer::hex($utxo, 32), 0);
$transaction = \BitWasp\Bitcoin\Transaction\TransactionFactory::build()
->spendOutPoint($outpoint)
->payToAddress($utxoAmount - $fee, $addressCreator->fromString($reciverPublicKey, $networkObject) )
->get();
echo "Unsigned transaction: " . $transaction->getHex() . '<BR><BR>';
$signScript = \BitWasp\Bitcoin\Script\ScriptFactory::scriptPubKey()->payToPubKeyHash($keyPairInput->getPublicKey()->getPubKeyHash());
$txOut = new \BitWasp\Bitcoin\Transaction\TransactionOutput($utxoAmount - $fee, $signScript);
$signer = new \BitWasp\Bitcoin\Transaction\Factory\Signer($transaction);
$signatureChecker = \Btccom\BitcoinCash\Transaction\Factory\Checker\CheckerCreator::fromEcAdapter( \BitWasp\Bitcoin\Bitcoin::getEcAdapter() ); // for version 0.0.35
$signer->setCheckerCreator( $signatureChecker ); // for version 0.0.35
$input = $signer->input(0, $txOut);
$signatureType = \Btccom\BitcoinCash\Transaction\SignatureHash\SigHash::ALL | \Btccom\BitcoinCash\Transaction\SignatureHash\SigHash::BITCOINCASH;
$input->sign($keyPairInput, $signatureType);
$signed = $signer->get();
echo "Witness serialized transaction: " . $signed->getHex() . '<BR><BR>';
echo "Base serialized transaction: " . $signed->getBaseSerialization()->getHex() . '<BR><BR>';
echo "Script validation result: " . ($input->verify() ? "yes\n" : "no\n"). '<BR><BR>';
die();
In this case I get the result:
Script validation result: no
Trying to broadcast the BCH transaction gives an error:
An error occured:
16: mandatory-script-verify-flag-failed (Signature must be zero for failed CHECK(MULTI)SIG operation). Code:-26
I think, it means, that signature is wrong. If we remove the flag $signatureType (keep this default), then Script validation result will be yes, but broadcasting will give an error:
16: mandatory-script-verify-flag-failed (Signature must use SIGHASH_FORKID). Code:-26
I think, it means - transaction signed as in bitcoin network, must to be signed by bitcoin-cash rules. Maybe I'm wrong. But bitcoin transaction signing is fine. Bitwasp has no manuals, how to sign a bitcoin-cash transactions, I have the same code for bitwasp v.0.0.34.2 (without addon "btccom/bitwasp-bitcoin-bch-addon", using $signer->redeemBitcoinCash(true); function) but it gives the same result.
It is interesting that in code of bitcoin-cash signer it takes the inner variable amount and include it in hash:
$hasher = new V1Hasher($this->transaction, $this->amount);
But for bitcoin bitwasp doesn't take the amount, presumably it takes an amount from the transaction.
Help me please to sign the transaction, bitwasp has only bitcoin examples, not bitcoin-cash. It is very difficult to find any informaion about php altcoins signing without third-party software. Regards.
This code to sign a bitcoin-cash transaction with PHP bitwasp v.0.0.35 library is works!
$unspendedTx = '49343e0a4ef29b819f87df1371c6f8eafa1f235074a27fb6aa5f4ab4c48e5c16';
$utxOutputIndex = 0;
$utxoPrivateKey = 'MyPrIvAtEKey';
$utxoAmount = 300000;
$reciverPublicKey = '1E8XaWNsCWyVaZaWTLh8uBdAZjLQqwWmzM';
$fee = 1000;
$networkObject = \Btccom\BitcoinCash\Network\NetworkFactory::bitcoinCash();
$outpoint = new \BitWasp\Bitcoin\Transaction\OutPoint(\BitWasp\Buffertools\Buffer::hex($unspendedTx, 32), $utxOutputIndex /* index of utxo in transaction, generated it */);
$destination = \BitWasp\Bitcoin\Script\ScriptFactory::scriptPubKey()->payToPubKeyHash( (new \Btccom\BitcoinCash\Address\AddressCreator())->fromString($reciverPublicKey)->getHash() );
$transaction = \BitWasp\Bitcoin\Transaction\TransactionFactory::build()
->spendOutPoint($outpoint)
->output($utxoAmount - $fee, $destination)
->get();
echo "Unsigned transaction: " . $transaction->getHex() . '<BR><BR>';
$keyPairInput = \BitWasp\Bitcoin\Key\PrivateKeyFactory::fromWif($utxoPrivateKey, null, $networkObject);
$txOut = new \BitWasp\Bitcoin\Transaction\TransactionOutput($utxoAmount, \BitWasp\Bitcoin\Script\ScriptFactory::scriptPubKey()->payToPubKeyHash( $keyPairInput->getPubKeyHash() ) );
$signer = new \BitWasp\Bitcoin\Transaction\Factory\Signer($transaction);
$signatureChecker = \Btccom\BitcoinCash\Transaction\Factory\Checker\CheckerCreator::fromEcAdapter( \BitWasp\Bitcoin\Bitcoin::getEcAdapter() ); // for version 0.0.35
$signer->setCheckerCreator( $signatureChecker ); // for version 0.0.35
$input = $signer->input(0, $txOut);
$signatureType = \Btccom\BitcoinCash\Transaction\SignatureHash\SigHash::ALL | \Btccom\BitcoinCash\Transaction\SignatureHash\SigHash::BITCOINCASH;
$input->sign($keyPairInput, $signatureType);
$signed = $signer->get();
echo "Transaction: " . $signed->getHex() . '<BR><BR>';
die();
I had broadcasted this PHP-generated test transaction, see link to tx. Problaly the problem was in
->payToAddress($utxoAmount - $fee, $addressCreator->fromString($reciverPublicKey, $networkObject) )
Maybe payToAddress has a bug, because "hand" script creation gives another transaction. Second:
$txOut = new \BitWasp\Bitcoin\Transaction\TransactionOutput($utxoAmount - $fee, $signScript);
We must to create tx input(previous output) without the fee.
Used libraries ( composer.json ):
{
"require" : {
"php" : ">=7.0",
"bitwasp/bitcoin": "0.0.35.0",
"btccom/bitwasp-bitcoin-bch-addon" : "0.0.2"
}
}
Hope, this will help for all altcoin api creators on PHP.
I am trying to implement CommWeb on my PHP site. It isn't working. I am getting following error message:
HTTP Status - 400
E5000: Required field vpc_AccessCode was not present in the request
How can I fix this? I haven't found anything helpful in the documentation.
Here is my code:
<?php
//Merchant Admin URL: https://migs.mastercard.com.au/ma/CBA
//Merchant ID: TEST
//Operator ID: Admin
//Password: d#test
// Access Code AEFTEST 1A22FTESTTEST
$session_id = 1;
$finalprice = 50;
$testarr = array(
"vpc_Amount" => $finalprice*100,//Final price should be multifly by 100
"vpc_AccessCode" => "AEFTEST",//Put your access code here
"vpc_Command"=> "pay",
"vpc_Locale"=> "en",
"vpc_MerchTxnRef"=> "CLI".$session_id, //This should be something unique number, i have used the session id for this
"vpc_Merchant"=> "TEST",//Add your merchant number here
"vpc_OrderInfo"=> "1A22FTESTTEST",//this also better to be a unique number
"vpc_ReturnURL"=> "http://localhost/test1/index.php/commweb/",//Add the return url here so you have to code here to capture whether the payment done successfully or not
"vpc_Version"=> "1");
ksort($testarr); // You have to ksort the arry to make it according to the order that it needs
$SECURE_SECRET = "d#test";//Add the secure secret you have get
$securehash = $SECURE_SECRET;
$url = "https://migs.mastercard.com.au/ma/CBA";
foreach ($testarr as $key => $value)
{
$securehash .= $value;
$url .= $key."=".urlencode($value)."&";
}
$securehash = md5($securehash);//Encoding
$url .= "vpc_SecureHash=".$securehash;
header("location:https://migs.mastercard.com.au/vpcpay?$url");
?>