I want to integrate the payment partal without displaying the MasterCard interface to user the will only fill their information on my web
here
my portal
and not here
mastercard portal
I am trying to implement CommWeb on my PHP site using curl. It isn't working. I am getting following error message:
if ($_SERVER["REQUEST_METHOD"] == "GET") {
if (!isset($_GET['id']) || !isset($_GET['motif']) || !isset($_GET['code'])){
die("Invalid request");
}
$amount = 10000;
$id = 2;
$motif = 'save';
$action_code = 'ookkk';
$orderInfo = 'fhhsd'.$id;
$MerchTxnRef = $orderInfo.'-'.generateMerchTxnRef();
$accountData = array(
'merchant_id' => 'TESTID', // for test card
'access_code' => '77867878', // for test card
'secret' => 'TYUJHGFDFGHJ87654567GFDFGHGF' // for test card
);
$currency_str = "USD";
$mult = 100;
$queryData = array(
'vpc_AccessCode' => $accountData['access_code'],
'vpc_Merchant' => $accountData['merchant_id'],
'vpc_Amount' => 1000000, // Multiplying by 100 to convert to the smallest unit
'vpc_OrderInfo' => $orderInfo,
'vpc_MerchTxnRef' => $MerchTxnRef,
'vpc_Command' => 'pay',
'vpc_Currency' => $currency_str,
'vpc_Locale' => 'en',
'vpc_Version' => 2,
'vpc_ReturnURL' => ('http://theeventsfactory.biz/the_events_factory/logics/payment_return.php?id='.$id.'&motif='.$motif.'&code='.$action_code),
'vpc_SecureHashType' => 'SHA256',
'vpc_CardNum' => '5123456789012346',
'vpc_CardExp' => '0521',
'vpc_CardSecurityCode'=> '123'
);
// Add secure secret after hashing
// $queryData['vpc_SecureHash'] = generateSecureHash($accountData['secret'], $queryData);
// $migsUrl = 'https://migs.mastercard.com.au/vpcpay?'.http_build_query($queryData);
$ch = curl_init("https://migs.mastercard.com.au/vpcdps");
curl_setopt_array($ch, array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $queryData,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false
));
$response = curl_exec($ch);
print_r($response);
}
function generateMerchTxnRef() {
$txnRef = rand(9, 9999999999999999);
// Saved in the database associated with the order id
return $txnRef;
}
function generateSecureHash($secret, array $params) {
$secureHash = "";
// Sorting params first based on the keys
ksort($params);
foreach ($params as $key => $value)
{
// Check if key equals to vpc_SecureHash or vpc_SecureHashType to discard it
if(in_array($key, array('vpc_SecureHash', 'vpc_SecureHashType'))) continue;
// If key either starts with vpc_ or user_
if(substr( $key, 0, 4 ) === "vpc_" || substr($key, 0, 5) === "user_") {
$secureHash .= $key."=".$value."&";
}
}
// Remove the last `&` character from string
$secureHash = rtrim($secureHash, "&");
//
return strtoupper(hash_hmac('sha256', $secureHash, pack('H*', $secret)));
}
This is the response i am receiving
vpc_Amount=0&vpc_BatchNo=0&vpc_Locale=en&vpc_Message=Required+field+vpc_Merchant+was+not+present+in+the+request&vpc_TransactionNo=0&vpc_TxnResponseCode=7
How will i solve this problem
You need to convert the array to a url encoded string with http_build_query
after setting the queryData array, add
$queryData_string = http_build_query($queryData);
Then the curlpost would be set to that
CURLOPT_POSTFIELDS => $queryData_string,
Related
I made a API to fetch and store data, I can fetch data without problem, but everything changes when I try to store data, when I send the data it returns [{"success":"0"}]. In the beginning it worked well, used accepted to store data, but suddenly everything changed. I've tried everything, compare the new with the old, changed the code, tables, but even so it always returns [{"success":"0"}] after comparing both (old and new) code I couldn't see much difference. What could I be doing wrong?
Insert data:
function insertloin()
{
if(isset($_POST["loincode"]))
{
$form_data = array(
':loincode' => $_POST["loincode"],
':code' => $_POST["code"],
':specie' => $_POST["specie"],
':grade' => $_POST["grade"],
':vesselname' => $_POST["vesselname"],
':type' => $_POST["type"],
':productformat' => $_POST["productformat"],
':dateprocessed' => $_POST["dateprocessed"],
':datebb' => $_POST["datebb"],
':projectcode' => $_POST["projectcode"],
':netweight' => $_POST["netweight"],
':producttype' => $_POST["producttype"],
':oldoc' => $_POST["oldoc"]
);
$query = "
INSERT INTO loins
(loincode, code, specie, grade, vesselname, type, productformat, dateprocessed, datebb, projectcode, netweight, producttype, oldoc) VALUES
(:loincode, :code, :specie, :grade, :vesselname, :type, :productformat, :dateprocessed, :datebb, :projectcode, :netweight, :producttype, :oldoc)
";
$statement = $this->connect->prepare($query);
if($statement->execute($form_data))
{
$data[] = array(
'success' => '1'
);
}
else
{
$data[] = array(
'success' => '0'
);
}
}
else
{
$data[] = array(
'success' => '0'
);
}
return $data;
}
Test:
if($_GET["action"] == 'insertloin')
{
$data = $api_object->insertloin();
}
Action:
if(isset($_POST["action"]))
{
if($_POST["action"] == 'insertloin')
{
$form_data = array(
'loincode' => $_POST["loincode"],
'code' => $_POST["code"],
'specie' => $_POST["specie"],
'grade' => $_POST["grade"],
'vesselname' => $_POST["vesselname"],
'type' => $_POST["type"],
'productformat' => $_POST["productformat"],
'dateprocessed' => $_POST["dateprocessed"],
'datebb' => $_POST["datebb"],
'projectcode' => $_POST["projectcode"],
'netweight' => $_POST["netweight"],
'producttype' => $_POST["producttype"],
'oldoc' => $_POST["oldoc"]
);
$api_url = "http://192.168.85.160/API/v2/api/test_api.php?action=insertloin";
$client = curl_init($api_url);
curl_setopt($client, CURLOPT_POST, true);
curl_setopt($client, CURLOPT_POSTFIELDS, $form_data);
curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($client);
curl_close($client);
$result = json_decode($response, true);
foreach($result as $keys => $values)
{
if($result[$keys]['success'] == '1')
{
echo 'insert';
}
else
{
echo 'error';
}
}
}
Please, help me find the bug.
Kind regards,
Abd
When $statement->execute() returns a false value it means your SQL had some sort of error. But you ignore that false value and instead return the same success status in both your if and your else clause.
To see your error codes try something like this:
if($statement->execute($form_data))
{
$data[] = array(
'success' => '1'
);
}
else
{
echo $statement->errorInfo();
print_r ( $statement->errorInfo() );
die(1);
}
You'll need to look at the error codes you get to see what's wrong and then do something smarter than echo / print_r / die.
I have some election data that's formatted in a text document and separated by commas that I'm trying to reformat for our website using PHP.
The text file is protected with a user name and password, so I'm trying to figure out how to extract the data into an array to manipulate. Here's the link (https://go.elections.hawaii.gov/media-results/files/summary.txt), but I pulled a sample of the data here for reference (http://lilly-digital.com/test/summary.txt).
Using the code below, I was able to produce this table, but I need to reorder and exclude some of the data: https://lilly-digital.com/test/parse.php Any suggestions on how to do that, too?
<?php
$filename = 'https://lilly-digital.com/test/summary.txt';
$the_big_array = [];
if (($h = fopen("{$filename}", "r")) !== FALSE)
{
while (($data = fgetcsv($h, 1000, ",")) !== FALSE)
{
$the_big_array[] = $data;
}
// Close the file
fclose($h);
}
$build = '<table><tbody>';
foreach($the_big_array as $row)
{
$build .= '<tr>';
foreach($row as $item)
{
$build .= "<td>{$item}</td>";
}
$build .= '</tr>';
}
$build .= '</tbody></table>';
echo $build;
?>
In summary, any idea how to extract the data using the username and password and reformat the data? I'm relatively new to this.
Thanks in advance.
Authentication code Used from Ariful Islam's answer
$https_user = "user_name";
$https_password = "password";
$opts = array('http' =>
array(
'method' => 'GET',
'header' => "Content-Type: text/xml\r\n".
"Authorization: Basic ".base64_encode("$https_user:$https_password")."\r\n",
'content' => $body,
'timeout' => 60
)
);
Once authenticated, you should try array_combine function which will create an array with keys containing fieldnames and values containing fielddata for the Mysql table. The code will be like:
$fileUrl = 'https://lilly-digital.com/test/summary.txt';
$delimiter=',';
$header = NULL;
$data = array();
if (($handle = fopen($fileUrl, 'r')) !== FALSE){
while (($row = fgetcsv($handle,0, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
The output would be similar to following
Array
(
[0] => Array
(
[Contest ID] => 2
[Contest Title] => U.S. Representative, Dist I - D
[Contest Seq Nbr] => 2
[Contest Type] => OF
[Contest Party] =>
[Absentee Mail Blank Votes] => 0
[Absentee Walk-in Blank Votes] => 0
[Election Blank Votes] => 0
[Absentee Mail Over Votes] => 0
[Absentee Walk-in Over Votes] => 0
[Election Over Votes] => 0
[Registered Voters] => 795248
[Total Precincts] => 115
[Counted Precincts] => 0
[Candidate ID] => 9
[Candidate Name] => CASE, Ed
[Candidate Seq Nbr] => 1
[Candidate Party] =>
[Absentee Mail Votes] => 0
[Absentee Walk-in Votes] => 0
[Election Votes] => 0
[Total Votes] => 0
)
[1] => Array ... so on
To insert into the database, you need to use the following code
$fields = implode("','",$header);
$fields = "'".$fields."'";
foreach($data as $key => $value) {
$value = implode("','",$value);
$value = "'".$value."'";
$sql = "INSERT INTO TABLENAME ($fields) VALUES ($value)";
}
Note: It is highly recommended to use Mysql Prepared statement. You can use the above logic while implementing it.
Server is protected using HTTP Basic Authentication so you need to pass a username and password along with the request. You can do that with stream_context_create
$username='Roland';
$password='Orzabal';
$auth = base64_encode("$username:$password");
$header = array("Authorization: Basic $auth");
$opts = array( 'http' => array ('method'=>'GET', 'header'=>$header));
$ctx = stream_context_create($opts);
//stream context is ready
$filename = 'https://lilly-digital.com/test/summary.txt';
$the_big_array = [];
stream context is the last optional parameter in fopen
if (($h = fopen("{$filename}", "r", false, $context)) !== FALSE)
{
//stuff
}
//other stuff
You can try following code:
$https_user = "user_name";
$https_password = "password";
$opts = array('http' =>
array(
'method' => 'GET',
'header' => "Content-Type: text/xml\r\n".
"Authorization: Basic ".base64_encode("$https_user:$https_password")."\r\n",
'content' => $body,
'timeout' => 60
)
);
$https_server = 'https://lilly-digital.com/test/summary.txt';
$context = stream_context_create($opts);
$url = $https_server;
$result = file_get_contents($url, false, $context);
$line_array = explode(PHP_EOL, $result);
$final_result = array_map(function($val) {
return explode(',', $val);
}, $line_array);
$final_result will represent a multi-dimensional array. Process this array as your need
I'm trying to get the response of A SOAP Service, but I can't get the subcollections data.
When I call the ws method using a soap client software I get the next response:
<WSGLMSuit.METHODNAME xmlns="http://tempuri.org/">
<Sdtpolizadetalle>
<Empresa>1</Empresa>
<DscEmpresa>TEST</DscEmpresa>
<Rama>22</Rama>
<DscRama>COMBINADO FAMILIAR</DscRama>
<Poliza>000000</Poliza>
<DscRiesgo/>
<InicioVigencia>2019-03-18</InicioVigencia>
<FinVigencia>2019-09-18</FinVigencia>
<Productor>3311</Productor>
<NombreProductor>TEST</NombreProductor>
<Tomador>
<CodTomador>336028</CodTomador>
<NombreTomador>TEST</NombreTomador>
<Domicilio>SAAVEDRA 1174 Dpto. 0</Domicilio>
<Localidad>TRES ARROYOS</Localidad>
<CodigoPostal>7500</CodigoPostal>
</Tomador>
<DscMoneda>PESOS</DscMoneda>
<CantidadCuotas>3</CantidadCuotas>
<Suplementos>
<Suplemento>
<Suplemento>0</Suplemento>
<TipoOperacion>02</TipoOperacion>
<SubTipoOperacion>000</SubTipoOperacion>
<DscOperacion>GENERAL</DscOperacion>
<InicioVigencia>2019-03-18</InicioVigencia>
<FinVigencia>2019-09-18</FinVigencia>
<Prima>2515.95</Prima>
<Premio>3104.68</Premio>
<Cuotas>
<Cuota>
<NroCuota>1</NroCuota>
<Vencimiento>2019-03-18</Vencimiento>
<Estado>Pagada</Estado>
<Importe>519.68</Importe>
<NroCupon>1</NroCupon>
</Cuota>
<Cuota>
<NroCuota>2</NroCuota>
<Vencimiento>2019-04-18</Vencimiento>
<Estado>Vencida</Estado>
<Importe>517.00</Importe>
<NroCupon>2</NroCupon>
</Cuota>
<Cuota>
<NroCuota>3</NroCuota>
<Vencimiento>2019-05-18</Vencimiento>
<Estado>Impaga</Estado>
<Importe>517.00</Importe>
<NroCupon>3</NroCupon>
</Cuota>
</Cuotas>
</Suplemento>
</Suplementos>
</Sdtpolizadetalle>
<Sesionexpirada>false</Sesionexpirada>
</WSGLMSuit.METHODNAMEResponse>
So, I made a function in PHP with SoapClient class to make same request and get the result parsed as JSON but it doesn't giving me the "Suplementos" collection and its data.
{
"Sdtpolizadetalle": {
"Empresa": 1,
"DscEmpresa": "TEST",
"Rama": 22,
"DscRama": "COMBINADO FAMILIAR",
"Poliza": 129031,
"DscRiesgo": "",
"InicioVigencia": "2019-03-18",
"FinVigencia": "2019-09-18",
"Productor": 3311,
"NombreProductor": "TEST",
"Tomador": {
"CodTomador": 336028,
"NombreTomador": "TEST",
"Domicilio": "SAAVEDRA 1174 Dpto. 0",
"Localidad": "TRES ARROYOS",
"CodigoPostal": "7500"
},
"DscMoneda": "PESOS",
"CantidadCuotas": 3,
"Suplementos": {} // <--- HERE IS THE ISSUE
},
"Sesionexpirada": false
}
The PHP function is:
$wsdl = "http://wsdlservice.org?wsdl";
$params = $request->getParsedBody();
$options = array(
'soap_version' => SOAP_1_2,
'style' => SOAP_DOCUMENT,
'use' => SOAP_LITERAL,
'exceptions' => true,
'trace' => 1,
'cache_wsdl' => WSDL_CACHE_NONE,
'encoding' => 'UTF-8'
);
$soap = new SoapClient($wsdl, $options);
$clientRes = $soap->METHODNAME($params);
return json_encode($clientRes, JSON_PRETTY_PRINT);
Finally I got a solution. I found a function for parsing XML string to Array. So what I do is get the response as XML, save it into a file and parse it with that function. Code better than words:
function xmlToArray($xml, $options = array())
{
$defaults = array(
'namespaceSeparator' => ':',
'attributePrefix' => '#',
'alwaysArray' => array(),
'autoArray' => true,
'textContent' => '$',
'autoText' => true,
'keySearch' => false,
'keyReplace' => false
);
$options = array_merge($defaults, $options);
$namespaces = $xml->getDocNamespaces();
$namespaces[''] = null;
$attributesArray = array();
foreach ($namespaces as $prefix => $namespace) {
foreach ($xml->attributes($namespace) as $attributeName => $attribute) {
if ($options['keySearch']) $attributeName =
str_replace($options['keySearch'], $options['keyReplace'], $attributeName);
$attributeKey = $options['attributePrefix']
. ($prefix ? $prefix . $options['namespaceSeparator'] : '')
. $attributeName;
$attributesArray[$attributeKey] = (string)$attribute;
}
}
$tagsArray = array();
foreach ($namespaces as $prefix => $namespace) {
foreach ($xml->children($namespace) as $childXml) {
$childArray = xmlToArray($childXml, $options);
list($childTagName, $childProperties) = each($childArray);
if ($options['keySearch'])
$childTagName = str_replace($options['keySearch'], $options['keyReplace'], $childTagName);
if ($prefix)
$childTagName = $prefix . $options['namespaceSeparator'] . $childTagName;
if (!isset($tagsArray[$childTagName])) {
$tagsArray[$childTagName] =
in_array($childTagName, $options['alwaysArray']) || !$options['autoArray']
? array($childProperties)
: $childProperties;
} elseif (
is_array($tagsArray[$childTagName]) && array_keys($tagsArray[$childTagName])
=== range(0, count($tagsArray[$childTagName]) - 1)
) {
$tagsArray[$childTagName][] = $childProperties;
} else {
$tagsArray[$childTagName] = array($tagsArray[$childTagName], $childProperties);
}
}
}
$textContentArray = array();
$plainText = trim((string)$xml);
if ($plainText !== '') $textContentArray[$options['textContent']] = $plainText;
$propertiesArray = !$options['autoText'] || $attributesArray || $tagsArray || ($plainText === '')
? array_merge($attributesArray, $tagsArray, $textContentArray) : $plainText;
return array(
$xml->getName() => $propertiesArray
);
}
$params = array('key' => 'value') // params needed to make the request
$options = array(
'trace' => 1,
'exceptions' => true
);
try {
$soap = new SoapClient($url, $options);
$soap->method($params); // replace method name
$xmlResponse = $soap->__getLastResponse();
} catch (Exception $e) {
die(
json_encode(
[
'error' => 'Cannot request to WS. ' . $e->getMessage()
]
)
);
// save the response into an xml file for parse
// it and return its content as json
if (file_put_contents('response.xml', $xmlResponse)) {
$xmlNode = simplexml_load_file($this->tempPath);
$arrayData = xmlToArray($xmlNode);
unlink('response.xml');
return json_encode($arrayData, JSON_PRETTY_PRINT);
} else {
return json_encode(['error' => 'Error saving the response into file.']);
}
I created this piece of code to use Google Analytics Measurement Protocol instead of the google provided javascript, analytics.js in one of my page.
Recently I was playing with analytics javascript code, and I found that many times it will not collect data if something is blocking tracking codes (eg.: analytics.js) like when PrivDog is installed (amongs others).
The original idea is coming from here, but this is for wordpress.
http://www.stumiller.me/implementing-google-analytics-measurement-protocol-in-php-and-wordpress/
I modified the code to send data with sockets. (and without the wordpress functions library)
$gclid = $_GET['gclid'];
if (!empty($gclid)) {
setcookie("gclid", $gclid, time() + (10 * 365 * 24 * 60 * 60));
}
// Handle the parsing of the _ga cookie or setting it to a unique identifier
function gaParseCookie()
{
if (isset($_COOKIE['_ga'])) {
list($version, $domainDepth, $cid1, $cid2) = split('[\.]', $_COOKIE["_ga"], 4);
$contents = array('version' => $version, 'domainDepth' => $domainDepth, 'cid' => $cid1 . '.' . $cid2);
$cid = $contents['cid'];
} else {
$cid = gaGenUUID();
}
return $cid;
}
// Generate UUID v4 function - needed to generate a CID when one isn't available
function gaGenUUID()
{
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
// 32 bits for "time_low"
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
// 16 bits for "time_mid"
mt_rand(0, 0xffff),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand(0, 0x0fff) | 0x4000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand(0, 0x3fff) | 0x8000,
// 48 bits for "node"
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
function gaBuildHit($method = null, $info = null)
{
global $gclid;
if ($method && $info) {
// Standard params
$v = 1;
$tid = "UA-XXXXXXX-XX"; // Put your own Analytics ID in here
$cid = gaParseCookie();
if (empty($gclid)) {
$gclid = $_COOKIE['gclid'];
}
// Register a PAGEVIEW
if ($method === 'pageview') {
// Send PageView hit
$data = array(
'v' => $v,
'tid' => $tid,
'cid' => $cid,
'gclid' => $gclid,
't' => 'pageview',
'dt' => $info['title'],
'dp' => $info['slug']
);
gaFireHit($data);
} // end pageview method
//
// Register an ECOMMERCE TRANSACTION (and an associated ITEM)
else if ($method === 'ecommerce') {
// Send Transaction hit
$data = array(
'v' => $v,
'tid' => $tid,
'cid' => $cid,
'gclid' => $gclid,
't' => 'transaction',
'ti' => $info['tid'], // Transaction ID
'ta' => 'SI',
'tr' => $info['price'], // transaction value (native currency)
'ts' => $info['shipping'], // transaction shipping (native currency)
'cu' => $info['cc'] // currency code
);
gaFireHit($data);
// Set up Item params
if ($info['info']->product_name) {
$in = urlencode($info['info']->product_name); // item name;
$ip = $tr;
$iq = 1;
$ic = urlencode($info['info']->product_id); // item SKU
$iv = urlencode('SI'); // Product Category - we use 'SI' in all cases, you may not want to
// Send Item hit
$data = array(
'v' => $v,
'tid' => $tid,
'cid' => $cid,
'gclid' => $gclid,
't' => 'item',
'ti' => $ti,
'in' => $in,
'ip' => $ip,
'iq' => $iq,
'ic' => $ic,
'iv' => $iv,
'cu' => $cu
);
gaFireHit($data);
}
} else if ($method === 'event') {
$data = array(
'v' => $v,
'tid' => $tid,
'cid' => $cid,
'gclid' => $gclid,
'ec' => $info['category'],
'ea' => $info['event'],
'el' => $info['label'],
'ev' => $info['value']
);
gaFireHit($data);
}
}
}
// See ttps://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
function gaFireHit($data = null)
{
if ($data) {
$url = 'https://ssl.google-analytics.com/collect';
$getString .= '?payload_data&';
$getString .= http_build_query($data);
$result = socketPost($url, $getString, $_SERVER['HTTP_USER_AGENT']);
return $result;
}
return false;
}
function socketPost($url, $post_string, $ua = null)
{
$parts = parse_url($url);
// workout port and open socket
$port = isset($parts['port']) ? $parts['port'] : 80;
$success = $fp = fsockopen($parts['host'], $port, $errno, $errstr, 30);
if ($fp) {
// create output string
$output = "POST " . $parts['path'] . " HTTP/1.1\r\n";
if (is_string($ua)) {
$output .= "User-Agent: " . $ua . "\r\n";
}
$output .= "Host: " . $parts['host'] . "\r\n";
$output .= "Content-Type: application/x-www-form-urlencoded\r\n";
$output .= "Content-Length: " . strlen($post_string) . "\r\n";
$output .= "Connection: Close\r\n\r\n";
$output .= isset($post_string) ? $post_string : '';
// send output to $url handle
$success = fwrite($fp, $output);
fclose($fp);
}
return $success ? true : false;
}
//examples:
//page hit
$data = array(
'title' => 'Page title',
'slug' => $_SERVER["REQUEST_URI"]
);
gaBuildHit('pageview', $data);
//ecommerce
$data = array(
'tid' => $order_id_in_merchant_system,
'cc' => 'AUD', // the currency code
'price' => $order_total, // the price
'shipping' => $order_shipping, // the shipping cost
'country' => 'AU' // the country ISO code
);
gaBuildHit('ecommerce', $data);
The code itself is working just fine. I put here for you to get the idea.
Question is, I dont really see the flow, how could an Adwords Click get tracked here. Like, if there is no _ga cookie set before (then gaParseCookie creates one), how could analytics connect the tracked event into eg.: an Analytics keyword the click coming from? Is that possible with Measurement Protocol?
Hey guys I am using open id authentication on my website and after authenticating I am getting a url from openid providers i.e yahoo and google
http://www.mysite.com/openid-login.php?
openid.identity=https://me.yahoo.com/a/1234567&
openid.ax.value.nickname=john&
openid.ax.value.email=john#yahoo.co.in&
http://www.mysite.com/openid-login.php?
openid.identity=https://www.google.com/accounts/o8/1234567&
openid.ext1.value.email=kevin#gmail.com&
openid.ext1.value.country=IN
I have trimmed the urls a bit for clarity. I would like to create a single function for both that can set the email(if exists), nickname(if exits), identity(openid ina ) in an array and return the values. eg.
function userdetails(array_get){
......
......
return $userdetails;
}
$userdetails =userdetails($_GET);
$userdetails['nickname'] would give me the nickname if exists and similarly for the email and identity. Thanks
I did not create this function nor take credit for it. This was pulled and modified from the Simple OpenID library. If somebody has a link please post it in the comments as I don't have access to the original source.
/**
* Method to filter through $_GET array for requested user information.
* Will return an array of trimmed userinfo.
*/
public function filterUserInfo($arr_get) {
$valid_ax_types = array('nickname' => 1, 'email' => 1, 'fullname' => 1, 'dob' => 1, 'gender' => 1, 'postcode' => 1, 'country' => 1, 'language' => 1, 'timezone' => 1, 'firstname' => 1, 'lastname' => 1);
$userinfo = array();
foreach ($arr_get as $key => $value) {
// trim the key
$trimmed_key = substr($key, strrpos($key, "_") + 1);
// check for valid openid_ext1 values
if (stristr($key, 'openid_ext1_value') && isset($value[1])) {
$userinfo[$trimmed_key] = $value;
}
// check for valid openid_ax values
if (stristr($key, 'openid_ax_value') && isset($value[1])) {
$userinfo[$trimmed_key] = $value;
}
// check for valid sreg_ values
else if (stristr($key, 'sreg_') && array_key_exists($trimmed_key, $arr_ax_types)) {
$userinfo[$trimmed_key] = $value;
}
}
return $userinfo;
}
I thought by "getting a url" you meant actually a URL. Accept the answer below me. :)
parse_url()
parse_str()
function userdetails( $url, $keep = array( 'email', 'nickname', 'identity' ) ) {
$array = parse_str( parse_url( $url, PHP_URL_QUERY ) );
$return = array();
foreach ( $keep as $key ) {
if ( isset( $array[ $key ] ) ) {
$return[ $key ] = $array[$key];
}
}
return $return;
}