POST API Issue - Not functioning - php

Good afternoon,
I'm having trouble with an api POST request - it simply isn't going anywhere, it's not showing on the API log at all - I've got various get requests which work fine but this one just doesn't - I'm unsure what I am doing wrong.
public function broadband_plan(){
$common = array();
$common['main_menu'] = 'Broadband plan';
$cli_or_postcode = isset($_GET["cli_or_postcode"]) ? $_GET["cli_or_postcode"] : "";
$district_id = isset($_GET["district_id"]) ? $_GET["district_id"] : "";
$sub_premises = isset($_GET["sub_premises"]) ? $_GET["sub_premises"] : "";
$premises_name = isset($_GET["premises_name"]) ? $_GET["premises_name"] : "";
$thoroughfare_number = isset($_GET["thoroughfare_number"]) ? $_GET["thoroughfare_number"] : "";
$thoroughfare_name = isset($_GET["thoroughfare_name"]) ? $_GET["thoroughfare_name"] : "";
$locality = isset($_GET["locality"]) ? $_GET["locality"] : "";
$postcode = isset($_GET["postcode"]) ? $_GET["postcode"] : "";
$nad_key = isset($_GET["nad_key"]) ? $_GET["nad_key"] : "";
$post_town = isset($_GET["post_town"]) ? $_GET["post_town"] : "";
$county = isset($_GET["county"]) ? $_GET["county"] : "";
$district_id = isset($_GET["district_id"]) ? $_GET["district_id"] : "";
$request = array();
$request['apiUsername'] = 'XXXXXXX';
$request['apiPassword'] = 'XXXXXXX';
$request['encryption'] = 'SHA-512';
$request['platform'] = 'LIVE';
$request['method'] = 'POST';
$address = '{
"sub_premises": $sub_premises,
"premises_name": $premises_name,
"thoroughfare_number": $thoroughfare_number,
"thoroughfare_name": $thoroughfare_name,
"post_town": $post_town,
"postcode": $postcode,
"district_id": $district_id,
"nad_key": $nad_key
}';
$address = json_encode($address);
$request['url'] = "/broadband/availability" . $address;
$broadband_plan_detail = array();
if (!empty($address)) {
$broadband_plan_detail = $this->get_plan($request);
}
return view('front.broadband_plan',compact('common','broadband_plan_detail'));
}

The $address after $address = json_encode($address); will be an object, it cannot be concatenated as a string in $request['url'] = "/broadband/availability" . $address;
Please check your API URL and ensure you follow their structure, for example if the API URL accept the parameters as GET request, you can pass the parameters likes:
$request['url'] = "/broadband/availability?sub_premises=" . $sub_premises . "&premises_name=" . $premises_name...
Base on your code, the API method is POST, so you might need to prepare the parameters as an array.

Related

How do I Pass plugin parameters to API code in PHP?

I have developed an API that works fine, but only when I plug in the parameters like "Phone" and "Amount". However, my goal is to pass these parameters from a plugin because those parameters will be different for every user. Below is how am trying to pass the parameters $phone_no and $amount, but its seems that am getting nowhere. Could you please tell me how these parameters can be passed successfully.
//Action Hook to trigger API call add_action('hrw_withdrawal_request_notification','mpesa_request_withdraw');
function mpesa_request_withdraw() {
$user = wp_get_current_user();
// Parameters to pass....
$phone_no = !empty($user->ID) ? get_user_meta($user->ID, 'hrw_phone_number', true) : '';
$amount = isset($_POST['hrw_withdrawal']['amount']) ?
hrw_sanitize_text_field($_POST['hrw_withdrawal']['amount']) : 0;
// API call begins here....
$endPoint = 'https://api.safaricom.co.ke/mpesa/b2c/v1/paymentrequest';
$B2C_ConsumerKey = "tttttttttttttttttttttttttttytr";
$B2C_ConsumerSecret = "gttttttttt";
$AccessToken = GenerateAccessToken($B2C_ConsumerKey, $B2C_ConsumerSecret);
$BusinessShortCode = 30013;
$PhoneNumber = $phone_no;
//$CallBackURL = "https://payments.dllion.store/B2C/callback.php";
$CallBackURL = "https://letawera.specctance.com/B2C/callback.php";
$TimeoutCallBackURL = "https://payments.dllion.store/B2C/callback.php";
$Amount = $amount;
$B2C_Initiator = "DEALLI";
$initiatorSecurityCredential =

Sync phonebook using php

I am working on web-service to sync contacts using yii2 framework. where i am having whole phone-book (in json array) from mobile end and i have to check which phone numbers are there in my database.
Request params would be something like this
{
"user_id": "4",
"user_details": [{
"first_name": "A",
"last_name": "A"
}, {
"first_name": "B",
"last_name": "B"
,
"mobile_number": ["(888) 888-888", "(777) 777-777"]
}, {
"first_name": "C",
"last_name": "C",
"mobile_number": ["+918000584123", "(666) 666-6666", "(555) 555-5555", "(444) 444-4444"]
}]
}
To achieve the functionality i have done following code.
public function actionSyncPhoneBook()
{
$amResponse = $amResponseData = [];
$snUserId = $this->amData['user_id'];// Here i will get user_id
if (!empty($this->omUser))
{
$userDetails = $this->amData['user_details'];//Here i will get array of user_details
$amAppContacts =[];
$amNonAppContacts = [];
//I have loop here of user details to scan mobile number array
foreach ($userDetails as $userKeys)
{
//In case if mobile number array is not given
if(!empty($userKeys["mobile_number"]))
{
// Loop for scanning mobile numbers
foreach ($userKeys["mobile_number"] as $key => $mobileNumber)
{
//regex for matching mobile number.
$phone = preg_replace('/[^a-zA-Z0-9+]/', '', $mobileNumber);
$oModelUser = Users::find()
->where(['phone' => $phone])
->one();
//Check if conttact is exists or not using exist method
$checkContactExists = Users::find()->where(['phone' => $phone])->exists();
if($checkContactExists == 1)
{
$oModelFriends = Friends::find()->where(["from_user_id"=>$snUserId,"to_user_id"=>$oModelUser->id])->asArray()->one();
$amCheckPhoneNumber['user_id'] = !empty((string)$oModelUser->id) ? (string)$oModelUser->id : '';
$amCheckPhoneNumber['first_name'] = !empty($oModelUser->first_name) ? $oModelUser->first_name : '';
$amCheckPhoneNumber['last_name'] = !empty($oModelUser->last_name) ? $oModelUser->last_name : '';
$amCheckPhoneNumber['email'] = !empty($oModelUser->email) ? $oModelUser->email : '';
$amCheckPhoneNumber['phone'] = !empty($oModelUser->phone) ? $oModelUser->phone : '';
$amCheckPhoneNumber['status'] = !empty((string)$oModelUser->status) ? (string)$oModelUser->status : '';
$amCheckPhoneNumber['relationship_status'] = !empty($oModelUser->relationship_status) ? $oModelUser->relationship_status : '';
$amCheckPhoneNumber['mobile_verified'] = !empty((string)$oModelUser->mobile_verified) ? (string)$oModelUser->mobile_verified : '';
$amCheckPhoneNumber['email_verified'] = !empty($oModelUser->email_verified) ? $oModelUser->email_verified : '';
$amCheckPhoneNumber['latitude'] = !empty($oModelUser->latitude) ? $oModelUser->latitude : "0";
$amCheckPhoneNumber['longitude'] = !empty($oModelUser->longitude) ? $oModelUser->longitude : "0";
if($oModelFriends["is_friend"] == 1)
{
$amCheckPhoneNumber['is_friend'] = "friends";
}
else
{
$amCheckPhoneNumber['is_friend'] = "no_friends";
}
//User Image
if(!empty($oModelUser->user_image))
{
if (filter_var($oModelUser->user_image, FILTER_VALIDATE_URL))
{
if(!empty($oModelUser->user_image))
{
$ssEventDetailsUserImage = $oModelUser->user_image;
}
else
{
$ssEventDetailsUserImage = Yii::$app->params['aws_cover_image_path'];
}
}
else
{
$ssEventDetailsUserImage =Yii::$app->params['aws_cover_image_path'];
}
}
else
{
$ssEventDetailsUserImage = Yii::$app->params['aws_cover_image_path'];
}
//Cover Image
if(!empty($oModelUser->cover_image))
{
if (filter_var($oModelUser->cover_image, FILTER_VALIDATE_URL))
{
if(!empty($oModelUser->cover_image))
{
$ssCoverImage = $oModelUser->cover_image;
}
else
{
$ssCoverImage = Yii::$app->params['aws_cover_image_path'];
}
}
else
{
$ssCoverImage =Yii::$app->params['aws_cover_image_path'];
}
}
else
{
$ssCoverImage = Yii::$app->params['aws_cover_image_path'];
}
$amCheckPhoneNumber['cover_image'] = !empty($ssCoverImage) ? $ssCoverImage : '';
$amCheckPhoneNumber['user_image'] = !empty($ssEventDetailsUserImage) ? $ssEventDetailsUserImage : '';
$amCheckPhoneNumber['app_user'] = "1";
//Final Response of users those who are using application
$amAppContacts[] = $amCheckPhoneNumber;
}
else
{
//Users who does not use application.
$otherUsers['user_id'] = !empty($userKeys['id']) ? $userKeys['id'] : '';
$otherUsers['first_name'] = !empty($userKeys['first_name']) ? $userKeys['first_name'] : '';
$otherUsers['last_name'] = !empty($userKeys['last_name']) ? $userKeys['last_name'] : '';
$otherUsers['email'] = !empty($userKeys['email']) ? $userKeys['email'] : '';
$otherUsers['phone'] = !empty($mobileNumber) ? $mobileNumber : '';
$otherUsers['status'] = !empty($userKeys['status']) ? $userKeys['status'] : '';
$otherUsers['relationship_status'] = !empty($userKeys['relationship_status']) ? $userKeys['relationship_status'] : '';
$otherUsers['user_image'] = Yii::$app->params['aws_cover_image_path'];
$otherUsers['cover_image'] = Yii::$app->params['aws_cover_image_path'];
$otherUsers['mobile_verified'] = !empty($userKeys['mobile_verified']) ? $userKeys['mobile_verified'] : '';
$otherUsers['email_verified'] = !empty($userKeys['email_verified']) ? $userKeys['email_verified'] : '';
$otherUsers['latitude'] = !empty($userKeys["latitude"]) ? $userKeys["latitude"] : "0";
$otherUsers['longitude'] = !empty($userKeys["longitude"]) ? $userKeys["longitude"] : "0";
$otherUsers['is_friend'] = "";
$otherUsers['app_user'] = "0";
//Final Response of users those who are not using app.
$amNonAppContacts[] = $otherUsers;
}
}
}
}
//Merging the app users and non-app users together.
$amResponseData = array_merge($amAppContacts,$amNonAppContacts);
$amResponse = Common:: successResponse("Sync your phonebook.",$amResponseData);
Common::encodeResponseJSON($amResponse);
}
}
From above code i am checking if mobile number is exist in the database than it will push into app users and rests will be in non-app users.
In my database mobile numbers are stored in the format of +(countryCode)(mobileNumber)
Example +918000584123
But it should also work if i don't pass +91 or any country codes.
It should work if mobile number array would be like
"mobile_number": ["(888) 888-888", "(777) 777-777"]
or it should be like
"mobile_number": ["+918000584123","+91 8000584123","8000584123", "(666) 666-6666", "(555) 555-5555", "(444) 444-4444"]
How to achieve this functionality?
Any help would be appreciated.
Thanks in advance.
dont need regex like this
$phone = preg_replace('/[^a-zA-Z0-9+]/', '', $mobileNumber);
Instead you can use
$phone = preg_replace('/[^0-9]/', '', $mobileNumber);
and change your where condition like this below. You should use LIKE condition
$oModelUser = Users::find()->where("phone LIKE'%".$phone."'")->one();
$checkContactExists = Users::find()->where("phone LIKE '%".$phone."'")->exists();
You tagged it with mysql, so I am answering from that angle.
The various phone number should be in a separate table, together with an id of the person they belong to. That way, there can be an arbitrary number of numbers for any person. I suggest 1:many, not many:many, and simply let the occasional shared phone be a dup number in the new table.
The table would have a non-unique index on number, thereby making it 'trivial' in SQL to locate the person(s) with a given number (or set of numbers, using IN).

Getting like and comment counts album of page facebook using graph api

Is there a way to check the number likes and comments on my page album? i have make request with this code:
$fields="id,name,description,link,cover_photo,count,likes.limit(0).summary(1),comments.limit(0).summary(1)";
$fb_page_id = "my page id";
$access_token="my access token";
$json_link = "https://graph.facebook.com/v2.7/{$fb_page_id}/albums?fields={$fields}&access_token={$access_token}";
$json = file_get_contents($json_link);
$obj = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);
for($x=0; $x<$album_count; $x++){
$id = isset($obj['data'][$x]['id']) ? $obj['data'][$x]['id'] : "";
$name = isset($obj['data'][$x]['name']) ? $obj['data'][$x]['name'] : "";
$url_name=urlencode($name);
$description = isset($obj['data'][$x]['description']) ? $obj['data'][$x]['description'] : "";
$link = isset($obj['data'][$x]['link']) ? $obj['data'][$x]['link'] : "";
$cover_photo = isset($obj['data'][$x]['cover_photo']['id']) ? $obj['data'][$x]['cover_photo']['id'] : "";
$count = isset($obj['data'][$x]['count']) ? $obj['data'][$x]['count'] : "";
$likes = count($obj['data'][$x]['likes']) ? $obj['data'][$x]['likes'] : "";
$comments = count($obj['data'][$x]['comments']) ? $obj['data'][$x]['comments'] : "";
But i cant get the data how many likes and comment on my specific album page facebook.
Please does anybody know how to get Facebook album like and comment counts? Many thanks in advance!

Laravel Request does not return result

I am using AWS and laravel 5.1.
I have two issues:
Most of the time API returns the expected result but sometimes server
doesn't return result for longer time. It might be due to the server
load(Although we don't have too much load on server).
Clients wait for few minutes and after that application crashes. Any
Advice.
If Client made an API request and before getting result, if device
loses internet connection. Server has process the data but unable to
deliver it to the client. how to handle this (Both in get as well as
post request)
Sample Code for first Part
public function psychometricResponses(Request $request)
{
$questionId=$request->get('questionId');
$answerId=$request->get('answerId');
$from = $request->has('from');
$userId = $request->has('id') ? $request->get('id') : 0;
$name = $request->has('name') ? $request->get('name') : '';
$email = $request->has('email') ? $request->get('email') : '';
$gender = $request->has('gender') ? $request->get('gender') : '';
$relationshipStatus = $request->has('relationshipStatus') ? $request->get('relationshipStatus') : '';
if($userId!=0){
$status = 1;
User::where('id',$userId)->update(['status'=>1]);
}else{
$status = 0;
}
$id = $this->calculatePersonality($questionId, $answerId, $userId, $from, $name, $email, $gender, $relationshipStatus);
return json_encode(['code'=>200,'message'=>"success",'response'=>array('personality'=>$this->_getPersonality($id),'psychometricId'=>$id,'status'=>$status)]);
}
public function calculatePersonality($questionId, $answerId, $userId, $from, $name, $email, $gender, $relationshipStatus)
{
//
$questionArray = explode(',', $questionId); //arraySize is 60
$answerArray = explode(',', $answerId); // //arraySize is 60
$this->questionAll = $this->_questionAll();
$personality = array('O'=>0,'C'=>0,'E'=>0,'A'=>0,'N'=>0);
for($i=0; $i<sizeof($answerArray);$i++){
$type = $this->_getQuestionType($questionArray[$i]);
if($type=='O'){
$personality['O'] = $answerArray[$i]=='1' ? $personality['O']+1 : $personality['O']-1;
}else if($type=='OR'){
$personality['O'] =$answerArray[$i]=='1' ? $personality['O']-1 : $personality['O']+1;
}else if($type=='C'){
$personality['C'] = $answerArray[$i]=='1' ? $personality['C']+1 : $personality['C']-1;
}else if($type=='CR'){
$personality['C'] = $answerArray[$i]=='1' ? $personality['C']-1 : $personality['C']+1;
}else if($type=='E'){
$personality['E'] = $answerArray[$i]=='1' ? $personality['E']+1 : $personality['E']-1;
}else if($type=='ER'){
$personality['E'] = $answerArray[$i]=='1'?$personality['E']-1 : $personality['E']+1;
}else if($type=='A'){
$personality['A'] = $answerArray[$i]=='1' ? $personality['A']+1 : $personality['A']-1;
}else if($type=='AR'){
$personality['A'] = $answerArray[$i]=='1' ? $personality['A']-1 : $personality['A']+1;
}else if($type=='N'){
$personality['N'] = $answerArray[$i]=='1'? $personality['N']+1 : $personality['N']-1;
}else if($type=='NR'){
$personality['N'] = $answerArray[$i]=='1' ? $personality['N']-1 : $personality['N']+1;
}
}
$mod = array();
$mod['O'] = abs($personality['O']);
$mod['C'] = abs($personality['C']);
$mod['E'] = abs($personality['E']);
$mod['A'] = abs($personality['A']);
$mod['N'] = abs($personality['N']);
arsort($mod);
$values = array_keys($mod);
$pTypeOne = $personality[$values[0]] < 0 ? $values[0].'R' : $values[0];
$pTypeTwo = $personality[$values[1]] < 0 ? $values[1].'R' : $values[1];
$pTypeThree = $personality[$values[2]] < 0 ? $values[2].'R' : $values[2];
$pTypeFour = $personality[$values[3]] < 0 ? $values[3].'R' : $values[3];
$pTypeFive = $personality[$values[4]] < 0 ? $values[4].'R' : $values[4];
$psychometricResponse = PsychometricResponse::create(array('typeA'=>$pTypeOne, 'valueA'=>$personality[$values[0]],'typeB'=>$pTypeTwo, 'valueB'=>$personality[$values[1]],
'typeC'=>$pTypeThree, 'valueC'=>$personality[$values[2]],'typeD'=>$pTypeFour, 'valueD'=>$personality[$values[3]],
'typeE'=>$pTypeFive, 'valueE'=>$personality[$values[4]],'questionId'=>$questionId,'answerId'=>$answerId, 'userId'=>$userId, 'from'=>$from,'name'=>$name,'email'=>$email, 'gender'=>$gender,'relationshipStatus'=>$relationshipStatus));
return $psychometricResponse->id;
}
private function _questionAll(){
$question = PsychometricQuestion::where('isActive',1)->get(['id','type']);
$result =array();
for($i=0;$i<sizeof($question);$i++){
$result[$question[$i]->id] = $question[$i]->type;
}
return $result;
}
private function _getQuestionType($id){
return $this->questionAll[$id];
}
private function _getPersonality($id){
$personality = PsychometricResponse::where('id',$id)->first(['typeA','typeB','typeC','typeD','typeE','valueA','valueB']);
$combined = array($personality->typeA,$personality->typeB);
sort($combined);
$combinedPersonality = PsychometricResult::where('type',$combined[0]."-".$combined[1])->first(['type','keyword','description','colorCode']); //Table PsychometricResult has 40 rows only.
$primaryPersonality = PsychometricResult::where('type',$personality->typeA)->first(['type','keyword','description','colorCode']);
$secondaryPersonality = PsychometricResult::where('type',$personality->typeB)->first(['type','keyword','description','colorCode']);
$permutation = $this->_getAllPermutation($personality);
$stylePersonality = PsychometricStyle::whereIn('type',$permutation)->get(['type','aspect','style','description']);
$primaryPercentage = round(abs($personality->valueA)/(abs($personality->valueA)+abs($personality->valueB)), 2);
$secondaryPercentage = 1 - $primaryPercentage;
return array('primaryPersonality'=>$primaryPersonality,'secondaryPersonality'=>$secondaryPersonality,'combinedPersonality'=>$combinedPersonality,
'styles'=>$stylePersonality,'primaryPercentage'=>$primaryPercentage,'secondaryPercentage'=>$secondaryPercentage);
}
private function _getAllPermutation($personality){
$combined = array($personality->typeA,$personality->typeB,$personality->typeC,$personality->typeD,$personality->typeE);
sort($combined);
$permutation = array();
for($i=0;$i<sizeof($combined);$i++){
for($j=$i+1;$j<5;$j++){
array_push($permutation,$combined[$i]."-".$combined[$j]);
}
}
return $permutation;
}

Search based on URL varibles

I want my search to focus on variables in the URL string. Currently it uses a form based search.
It uses this
<?php
include('db.php'); // include your code to connect to DB.
$tbl_name="mobile"; //your table name
$whereClauses = array();
if (! empty($_POST['Model'])) $whereClauses[] ="model='".mysql_real_escape_string($_POST['Model'])."'";
if (! empty($_POST['Mins'])) $whereClauses[] ="minutes='".mysql_real_escape_string($_POST['Mins'])."'";
if (! empty($_POST['Texts'])) $whereClauses[] ="texts='".mysql_real_escape_string($_POST['Texts'])."'";
if (! empty($_POST['Freegifts'])) $whereClauses[] ="free_gift='".mysql_real_escape_string($_POST['Freegifts'])."'";
if (! empty($_POST['Network'])) $whereClauses[] ="network_name='".mysql_real_escape_string($_POST['Network'])."'";
if (! empty($_POST['Merchant'])) $whereClauses[] ="merchant_category='".mysql_real_escape_string($_POST['Merchant'])."'";
$where = '';
if (count($whereClauses) > 0) { $where = ' WHERE '.implode(' AND ',$whereClauses); }
$sql = mysql_query("SELECT * FROM $tbl_name".$where);
?>
However, I have added this to my page:
<?php
$model = $_GET['model']; //gets model from URL
$mins = $_GET['mins']; //gets mins from URL
$texts = $_GET['texts']; //gets mins from URL
$freegift = $_GET['free-gift']; //gets mins from URL
$network = $_GET['network']; //gets mins from URL
$plan = $_GET['plan']; //gets mins from URL
?>
It needs to be so not all variables are required. Any help would be appreciated.
Thanks in advance :)
There are a number of options that will return value or NULL:
<?php
$model = (isset($_GET['model']) ? $_GET['model'] : NULL);
$mins = (isset($_GET['mins']) ? $_GET['mins'] : NULL);
$texts = (isset($_GET['texts']) ? $_GET['texts'] : NULL);
$freegift = (isset($_GET['free-gift']) ? $_GET['free-gift'] : NULL);
$network = (isset($_GET['network']) ? $_GET['network'] : NULL);
$plan = (isset($_GET['plan']) ? $_GET['plan'] : NULL);
?>
This will get the variables from their correponding $_GET element, only if there is one set.
Alternative syntax (shorter):
<?php
$model = ($_GET['model'] ? $_GET['model'] : NULL);
$mins = ($_GET['mins'] ? $_GET['mins'] : NULL);
$texts = ($_GET['texts'] ? $_GET['texts'] : NULL);
$freegift = ($_GET['free-gift'] ? $_GET['free-gift'] : NULL);
$network = ($_GET['network'] ? $_GET['network'] : NULL);
$plan = ($_GET['plan'] ? $_GET['plan'] : NULL);
?>
Alternative (untested though):
<?php
$vars = array('model','mins','texts','free-gift','network','plan');
foreach($vars as $value) {
$$value = (isset($_GET[$value]) ? $_GET[$value] : NULL);
}
?>
EDIT:
In order to set a WHERE clause based on it, I suggest:
<?php
$vars = array('model','mins','texts','free-gift','network','plan');
foreach($vars as $value) {
$$value = (isset($_GET[$value]) ? $_GET[$value] : NULL);
unset $vars[$value]; //sweeping the NULL ones
}
$where_clause = $vars[0]; //the only remaining value after previous cleanup
?>

Categories