libphonenumber for php - php

I am using https://github.com/davideme/libphonenumber-for-PHP for formatting phonenumbers
I am having issue with 1800 numbers
$formatnumber = "1800123456"
$country = "AU";
$phoneUtil = PhoneNumberUtil::getInstance();
try {
$NumberProto = $phoneUtil->parse( $formatnumber , $country );
} catch ( NumberParseException $e ) {
echo $e;
}
$formattedNumber = $phoneUtil->format( $NumberProto, PhoneNumberFormat::NATIONAL );
What I am expecting to get back from $formattedNumber is "1800 123456"
What I get back is an unformatted number "1800123456"
If there something I need to do doing to get it to format correctly?

It works for me with pretty much your code:
<?php
require __DIR__ . '/vendor/autoload.php';
$formatnumber = "1800123456";
$country = "AU";
$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
try {
$NumberProto = $phoneUtil->parse($formatnumber, $country);
} catch (NumberParseException $e) {
echo $e;
}
$formattedNumber = $phoneUtil->format($NumberProto, \libphonenumber\PhoneNumberFormat::NATIONAL);
echo $formattedNumber;
Response:
1800 123 456
I am using my version of libphonenumber-for-php though: https://github.com/giggsey/libphonenumber-for-php

Related

PHP Fatal error: Uncaught Unirest\Exception: Bad URL

I'm trying to request a REST API using PHP Unirest.
The printed error is the following:
Bad URL, colon is first character
And my code:
<?php
require __DIR__ . '/../vendor/autoload.php';
use Unirest\Request as UniRequest;
use CurlFile;
if (isset($_POST['primeiro'])) {
$where = $_POST["where"];
$equal = $_POST["equal"];
$resultado = new pedidos;
$valores = $resultado->LogIgualA($where, $equal);
}
class pedidos {
function LogIgualA($where, $equal) {
$wsURL = "localhost:8080/public";
try {
$valores = UniRequest::get($wsURL."/visual/json_log/where=".$where."/equal=".$equal, $headers, null);
} catch (Exception $e) {
echo $e->getMessage();
}
$valoresAux = $valores->body;
$valores = [];
foreach($valoresAux as $z){
$ID = $z->ID;
$DateConnection = $z->DateConnection;
$TimeToServe = $z->TimeToServe;
$ClientIP = $z->ClientIP;
$CacheCode = $z->CacheCode;
$Bytes = $z->Bytes;
$Method = $z->Method;
$RequestProtocol = $z->RequestProtocol;
$RequestIP = $z->RequestIP;
$RequestPort = $z->RequestPort;
$RequestFolder = $z->RequestFolder;
$Auth = $z->Auth;
$RouteLeft = $z->RouteLeft;
$RouteRight = $z->RouteRight;
$ContentType = $z->ContentType;
}
return $valores;
}
}
The "isset($_POST['primeiro']" is when I click the button in HTML so it calls the function in PHP.
I really don't know how to use this...
You need to prepend a protocol like https://.
There are other people having the same issue where prepending the protocol fixed this... https://github.com/Azure/doAzureParallel/issues/44
URL is not http: localhost:8080/public
Also check that there is no malicious input in your $_POST vars and maybe you need to use urlencode() on the fields containing appropriate characters.

php-on-couch get all records fast

With PHP-ON-COUCH, i try to get all records in couchdb with php-on-couch, but it's not works fastly.
require_once "lib/couch.php";
require_once "lib/couchClient.php";
require_once "lib/couchDocument.php";
$couch_dsn = "http://localhost:5984/";
$couch_db = "couch";
$client = new couchClient($couch_dsn,$couch_db);
$all_singers = $client->getAllDocs();
foreach ( $all_singers->rows as $row ) {
$doc = $client->getDoc($id);
echo $doc->singer;
echo $doc->title;
echo $doc->description;
}
Is there another method to do this properly?
thank you in advance
You're not using the functions correctly. What you're doing right now is extremly slow because your fetching all the docs then you fetch them again 1 by one with the (getDoc) function. When you query all docs, you get something like this:
{
"total_rows": 0,
"count": 0,
"rows": [{
"key": 1,
"value": "value",
"doc": {
"singer": "Foo",
"title": "bar"
}
}]
}
Here's a revised version of your code :
<?php
require_once "lib/couch.php";
require_once "lib/couchClient.php";
require_once "lib/couchDocument.php";
$couch_dsn = "http://localhost:5984/";
$couch_db = "couch";
$client = new couchClient($couch_dsn, $couch_db);
$all_singers = null;
try {
$all_singers = $client->include_docs(true)->getAllDocs();
} catch (Exception $e) {
//Handle the exception here.
}
if (!isset($all_singers) || !isset($all_singers->rows))
echo "No singers found";
else
foreach ($all_singers->rows as $row) {
if (isset($row->error))
continue; //Log the error or something like this
if (isset($row->doc)) {
$doc = $row->doc;
echo $doc->singer;
echo $doc->title;
echo $doc->description;
}
}

Paypal PHP SDK bulk payout

I am trying to test Paypals batch payout:
My code:
// ...
public function sendBatchPayment(array $payoutItems, $senderBatchId, $type= 'Email', $currency = 'CAD', $note = '') {
$payouts = new \PayPal\Api\Payout();
$senderBatchHeader = new \PayPal\Api\PayoutSenderBatchHeader();
$senderBatchHeader->setSenderBatchId($senderBatchId)
->setEmailSubject("You have a Payout!");
foreach ($payoutItems as $payoutItem) {
$emailExists = (isset($payoutItem['email']) && !empty($payoutItem['email']));
$amountExists = (isset($payoutItem['amount']) && !empty($payoutItem['amount']));
$senderItemIdExists = (isset($payoutItem['sender_item_id']) && !empty($payoutItem['sender_item_id']));
if(!$emailExists || !$amountExists || !$senderItemIdExists) continue;
$receiver = $payoutItem['email'];
$item_id = $payoutItem['sender_item_id'];
$value = (float) $payoutItem['amount'];
$senderItem = new \PayPal\Api\PayoutItem();
$senderItem->setRecipientType('Email')
->setNote('Your Payment')
->setReceiver($receiver)
->setSenderItemId($item_id)
->setAmount(new \PayPal\Api\Currency('{
"value":$value,
"currency":"CAD"
}'));
$payouts->setSenderBatchHeader($senderBatchHeader)
->addItem($senderItem);
} // EO foreach
$request = clone $payouts;
try {
$output = $payouts->create(null, $this->apiContext);
} catch (Exception $e) {
return $e->getMessage;
}
return $output;
}
But I keep getting a 400.
I suspect its due to this being inside the loop:
$payouts->setSenderBatchHeader($senderBatchHeader)
->addItem($senderItem);
when Paypals examples are like this:
$payouts->setSenderBatchHeader($senderBatchHeader)
->addItem($senderItem1)
->addItem($senderItem2);
;
How do I add items inside the loop?
EDIT:
Error:
PayPalConnectionException in PayPalHttpConnection.php line 180:
Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payouts?.
Thankyou.
I managed to fix the issue by changing the $senderBatchId value to just:
uniqid()
instead of:
uniqid() . microtime(true)
Paypal REST API does not like it that way for some reason. If a better programmer than I can explain this I will mark his/her answer are correct.

Integrate Sitelink using php

I want to integrate Sitelink with my website using php. For demo they have just provided this code
echo '<p>Testing SiteLink...</p>';
define( 'SITELINK_URL', "https://www.smdservers.net/CCWs_3.5/CallCenterWs.asmx?WSDL");
define( 'SITELINK_CORP_CODE', "CCTST" );
define( 'SITELINK_LOC_CODE', "Demo" );
define( 'SITELINK_CORP_LOGIN', "Administrator" );
define( 'SITELINK_CORP_PASS', "Demo" );
$client = new SoapClient( SITELINK_URL );
$params->sCorpCode = SITELINK_CORP_CODE;
$params->sLocationCode = SITELINK_LOC_CODE;
$params->sCorpUserName = SITELINK_CORP_LOGIN;
$params->sCorpPassword = SITELINK_CORP_PASS;
try
{
$units = $client->SiteInformation( $params );
$result = $units->SiteInformationResult;
}
catch (Exception $e )
{
die( 'Error: '.$e->getMessage().'<br>'.$e );
}
echo htmlentities( $result->any );
But I am not able to understand how to fecth the data and process it using php. I have to Fetch unit sizes and their respective prices. Any help is greatly appreciated. Thanks in advance.
You are not trying to get Units you are getting SiteInformation
add type for $params first:
$params = new stdClass; // as stdClass
$params->sCorpCode = SITELINK_CORP_CODE;
$params->sLocationCode = SITELINK_LOC_CODE;
$params->sCorpUserName = SITELINK_CORP_LOGIN;
$params->sCorpPassword = SITELINK_CORP_PASS;
then:
$units = $client->UnitTypePriceList($params);
$result = $units->UnitTypePriceListResult->any;
and you have to parse the data with DOMDocument, check the tag name you want to display and print it out:
$dom = new DOMDocument;
$dom->loadXML($result);
$xpath = new DOMXPath($dom);
$el = $xpath->query('//Table');
foreach($el as $units){
$UnitID = $xpath->query('UnitID_FirstAvailable', $units)->item(0)->nodeValue;
echo $UnitID;
}
I don't know what are your desired values, but I took UnitID_FirstAvailable as example.
SiteInformation is expecting array not Object and your $params was never declared
define('SITELINK_URL', "http://www.smdservers.net/CCWs_3.5/CallCenterWs.asmx?WSDL");
define('SITELINK_CORP_CODE', "CCTST");
define('SITELINK_LOC_CODE', "Demo");
define('SITELINK_CORP_LOGIN', "Administrator");
define('SITELINK_CORP_PASS', "Demo");
$client = new SoapClient(SITELINK_URL);
$params = array("sCorpCode" => SITELINK_CORP_CODE,"sLocationCode" => SITELINK_LOC_CODE,"sCorpUserName" => SITELINK_CORP_LOGIN,"sCorpPassword" => SITELINK_CORP_PASS);
try {
$units = $client->SiteInformation($params);
header("Content-Type: text/xml");
print($units->SiteInformationResult->any);
} catch ( Exception $e ) {
die('Error: ' . $e->getMessage() . '<br>' . $e);
}
See Live DEMO
I know this is kind of old, but I've been doing some extensive work with the API. First off, you'll want this: SiteLink API Documentation
To get all available units, you could do something like this:
// define API connection credentials
define('SITELINK_URL', "http://www.smdservers.net/CCWs_3.5/CallCenterWs.asmx?WSDL");
define('SITELINK_CORP_CODE', "CCTST");
define('SITELINK_LOC_CODE', "Demo");
define('SITELINK_CORP_LOGIN', "Administrator");
define('SITELINK_CORP_PASS', "Demo");
$client = new SoapClient( SITELINK_URL );
$params->sCorpCode = SITELINK_CORP_CODE;
$params->sLocationCode = SITELINK_LOC_CODE;
$params->sCorpUserName = SITELINK_CORP_LOGIN;
$params->sCorpPassword = SITELINK_CORP_PASS;
$params->lngLastTimePolled = 0;
$params->bTestMode = true;
try
{
$units = $client->UnitsInformationAvailableUnitsOnly_v2($params);
$result = $units->UnitsInformationAvailableUnitsOnly_v2Result;
}
catch (Exception $e)
{
die( 'Error: '.$e->getMessage().'<br />'.$e );
}
echo '<table>';
$formatUnits = new SimpleXMLElement($result->any);
foreach($formatUnits->NewDataSet->Table as $unit){
echo "<tr>\r\n";
echo "<td><a href='#' data-unit-number='".$unit->sUnitName."' data-unit-id='".$unit->UnitID."' data-rate='".$rate."' class='res-unit-link'>".$unit->sUnitName."</a></td>\r\n";
echo "<td>".$unit->sTypeName."</td>\r\n";
echo "</tr>\r\n";
}
echo '</table>';
You could do var_dump($formatUnits) to see all available data in the object that gets returned by SiteLink. The above code is an example from something I made where I used jQuery to grab all of the data- attributes from the link to use for the rental/reservation process.
I hope this helps somebody. I really could have used it when I first started using the API.

� char returned from Google currency API

Background:
I've created a website that displays currency rates from various countries. I use Google's currency converter API to perform the calculations.
http://www.google.com/ig/calculator?h1=en&q=9999gbp=?usd
Notice the query I have passed in e.g. 9999 Great British Pounds to United States Dollars.
The API returns:
{lhs: "9999 British pounds",rhs: "15 769.4229 U.S. dollars",error: "",icc: true}
Google has separated the 15 769.4229 with white space between the 5 and the 7.
This causes a problem when I return the results of a calculation on my site as the white space char is replaced with the � symbol.
See screen shot below:
Any ideas what this symbol is called so I can attempt to remove it?
<?php
// Check to ensure that form has been submitted
if (isset($_POST['amount'], $_POST['from'], $_POST['to'])) {
$amount = trim($_POST['amount']);
$from = $_POST['from'];
$to = $_POST['to'];
try {
$conversion = currency_convert($googleCurrencyApi, $amount, $from, $to);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage();
}
// Check URL has been formed
if ($conversion == false) {
echo 'Sorry, something went wrong';
} else {
echo $conversion[0], ' = ', $conversion[1];
}
}
function currency_convert($googleCurrencyApi, $amount, $from, $to) {
$result = file_get_contents($googleCurrencyApi . $amount . $from . '=?' . $to);
$expl = explode('"', $result);
if ($expl[1] == '' || $expl[3] == '') {
throw new Exception('An error has occured. Unable to get file contents');
} else {
return array(
$expl[1],
$expl[3]
);
}
}
?>
Here's my code so far at the moment, so you get the idea behind my logic.
This is most probably non-breaking space, try replacing into space:
$result = file_get_contents($googleCurrencyApi . $amount . $from . '=?' . $to);
$result = str_replace("\xA0", " ", $result);
Try modifying your code so that you're UTF8 decoding the data that's being returned from Google:
// Check URL has been formed
if ($conversion == false) {
echo 'Sorry, something went wrong';
} else {
echo utf8_decode($conversion[0]), ' = ', utf8_decode($conversion[1]);
}
I'm presuming that your default encoding is ISO-8859-1
EDIT
(As per comments) The issue may be that you have been sent a null character. Try this:
$result = str_replace("\0", "", $result );
or
$result = str_replace("", "", $result );
After str_replace do:
$result_amt = utf8_decode($amount);
You will get the ? character instead of space. So then use str_replace again to remove ? character:
$result =str_replace("?","", $result_amt );

Categories