AJAX post request to third party REST api - angularjs

. I am using laravel backend as API and angular as frontend which calls laravel api. Laravel api access the teamwork api through basic authentication using curl.
Now I am working with teamwork Api. Trying to create a comment using the API.
API documentation describes following.
{
"comment": {
"body": "Reply to earlier comment",
"notify": "",
"isprivate": false,
"pendingFileAttachments": "",
"content-type": "TEXT"
}
}
//ref : http://developer.teamwork.com/comments#creating_a_commen
in my ajax call i have used following
var data = $.param({
'body' : commentBodyValue, //variable
'notify': "",
'isPrivate':false,
"pendingFileAttachments": "",
"content-type": "TEXT"
});
My post does not give error, but it also do not create a new comment too. What am I missing? I think i failed to arrange data according to the format allowed in api. Can you kindly help me to fix it?
Edit:
Angular Controller:
//add new comment
$scope.addComment = function(taskId,commentAuthorId)
{
var commentBod = document.getElementById("commentBody");
var commentBodyValue = commentBod.value;
console.log("new comment : "+ taskId + commentBodyValue);
//submit the post request
//$http.post();
//using jquery function param to serialize
var data = $.param({
'body' : commentBodyValue,
'notify': "",
'isPrivate':false,
"pendingFileAttachments": "",
"content-type": "TEXT"
});
var config = {
headers : {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
}
var url = "http://abounde.com/portal/api/post_comment/"+taskId;
$http.post(url,data,config)
.then(
function(response){
//success
console.log("response : Submitted :D " + response);
},
function(response){
//failure
console.log(response);
}
);
}
Edit 2
Laravel route and controller
Routes:
//post comment to resource
Route::post('post_comment/{task_id}',[
'uses'=>'PortalController#postComment',
'as'=>'portal.client.postComment'
]);
Controller:
//post comment at task
public function postComment(Request $request, $task_id)
{
$secretApiKey = $request->session()->get('secretApiKey');
if(!empty($secretApiKey)){
//post the msg
$this->callTeamworkApi($secretApiKey,"tasks/".$task_id."/comments.json");
}else{
return response()->json(['response'=>"Not Logged In"]);
}
}
//authentication method
public function callTeamworkApi($secretApiKey, $apiCallString)
{
//cURL
$password = "xxx";
$channel = curl_init();
//options
curl_setopt($channel, CURLOPT_URL, "http://projects.abounde.com/".$apiCallString); // projects.json?status=LATE gets all late projects
curl_setopt($channel, CURLOPT_HTTPHEADER,
array(
"Authorization: Basic " . base64_encode($secretApiKey . ":" . $password)
));
$msg = curl_exec($channel);
curl_close($channel);
return response()->json(['res'=>$msg]);
}
EDIT 3: Contacted with teamwork Api support.
After their advice i came up with following code
//post comment at task
public function postComment(Request $request, $task_id)
{
$secretApiKey = $request->session()->get('secretApiKey');
if(!empty($secretApiKey)){
//post the msg
$comment=array();
// $comment['body']=$request->input('body');
// $comment['notify']=$request->input('notify');
// $comment['isprivate']=$request->input('isprivate');
// $comment['pendingFileAttachments']=$request->input('pendingFileAttachments');
// $comment['content-type']=$request->input('content-type');
$comment['comment']['body']="test";
$comment['comment']['notify']="";
$comment['comment']['isprivate']=false;
$comment['comment']['pendingFileAttachments']="";
$comment['comment']['content-type']="text";
$this->callTeamworkPostApi($secretApiKey,"tasks/".$task_id."/comments.json",json_encode($comment));
//var_dump($comment);
//return response()->json(['response'=>"Trying"]);
}else{
return response()->json(['response'=>"Not Logged In"]);
}
}
}
///
public function callTeamworkPostApi($secretApiKey, $apiCallString,$comment)
{
//cURL
$password = "xxx";
$channel = curl_init();
//options
curl_setopt($channel, CURLOPT_URL, "http://projects.abounde.com/".$apiCallString); // projects.json?status=LATE gets all late projects
curl_setopt($channel, CURLOPT_HTTPHEADER,
array(
"Authorization: Basic " . base64_encode($secretApiKey . ":" . $password)
));
curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($channel, CURLOPT_POSTFIELDS, $comment);
$msg = curl_exec($channel);
curl_close($channel);
var_dump($msg);
//return response()->json(['res'=>$msg]);
}
var_dump($comment) gives
string(107) "{"comment":{"body":"test","notify":"","isprivate":false,"pendingFileAttachments":"","content-type":"text"}}"
However the api still do not save the comment. It has to be a curl post method issue. Right?
Edit 4:
I have done a var_dump(curl_getinfo($channel));
this gave me following response.
array(26) { ["url"]=> string(55) "http://projects.abounde.com/tasks/8199861/comments.json" ["content_type"]=> NULL ["http_code"]=> int(500) ["header_size"]=> int(229) ["request_size"]=> int(311) ["filetime"]=> int(-1) ["ssl_verify_result"]=> int(0) ["redirect_count"]=> int(0) ["total_time"]=> float(0.5) ["namelookup_time"]=> float(0) ["connect_time"]=> float(0.109) ["pretransfer_time"]=> float(0.109) ["size_upload"]=> float(107) ["size_download"]=> float(0) ["speed_download"]=> float(0) ["speed_upload"]=> float(214) ["download_content_length"]=> float(0) ["upload_content_length"]=> float(107) ["starttransfer_time"]=> float(0.5) ["redirect_time"]=> float(0) ["redirect_url"]=> string(0) "" ["primary_ip"]=> string(13) "23.23.184.208" ["certinfo"]=> array(0) { } ["primary_port"]=> int(80) ["local_ip"]=> string(11) "192.168.0.6" ["local_port"]=> int(31657) }
The response code 500 may points to the fact that teamwork has some kind of internal issues.

The issue i found out is that you are not passing your comment data which you received from the frontend to the curl the request in callTeamworkApi().Try below code and see if you get your desired output or not
//post comment at task
public function postComment(Request $request, $task_id)
{
$secretApiKey = $request->session()->get('secretApiKey');
if(!empty($secretApiKey)){
//post the msg
$comment=array();
$comment['body']=$request->input('body');
$comment['notify']=$request->input('notify');
$comment['isPrivate']=$request->input('isprivate');
$comment['pendingFileAttachments']=$request->input('pendingFileAttachments');
$comment['content-type']=$request->input('content-type');
$this->callTeamworkApi($secretApiKey,"tasks/".$task_id."/comments.json",json_encode($comment));
}else{
return response()->json(['response'=>"Not Logged In"]);
}
}
//authentication method
public function callTeamworkApi($secretApiKey, $apiCallString,$comment)
{
//cURL
$password = "xxx";
$channel = curl_init();
//options
curl_setopt($channel, CURLOPT_URL, "http://projects.abounde.com/".$apiCallString); // projects.json?status=LATE gets all late projects
curl_setopt($channel, CURLOPT_HTTPHEADER,
array(
"Authorization: Basic " . base64_encode($secretApiKey . ":" . $password)
));
curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($channel, CURLOPT_POSTFIELDS, $comment);
$msg = curl_exec($channel);
curl_close($channel);
return response()->json(['res'=>$msg]);
}

Solution Found:
While calling to the teamwork API, it is essential that the content-type is set to Json. and the information should be in header file. header variable should be a multi array which takes authentication and content type information.
$headers = array();
$headers[] = "Authorization: Basic " . base64_encode($secretApiKey . ":" . $password);
$headers[] = "Content-Type: application/json";
//pass it as variable
curl_setopt($channel, CURLOPT_HTTPHEADER, $headers);
And then it works like charm.
returns following after creation of the comment.
{"commentId":"4294639","STATUS":"OK"}

Related

React-App Axios POST to php.file with sentMail ->works from localhost but empty $_Post['***'] from Server

I have an mail.php file in root on my hosting space.
Do I call mail.php with axios from my localhost from within the development server (npm start) it works fine.
The form who triggers the POST sends the data to my Email address.
After the build process and the upload on my web space, I still receive an email but there the input is missing.
Axios POST:
const formData = new FormData();
// formData.append('name', datas.name);
// formData.append('email', datas.email);
// formData.append('message', datas.message);
// formData.append('nice', nice)
formData.append('name', 'Klara');
formData.append('email', 'klara#gmail.com');
formData.append('message', 'Hallo');
//POST data to the php file
try{
axios.post('https://salevsky.net/mail.php', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
} catch(error) {
PHP file:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: multipart/form-data');
$to = "blablub#webyy.net";
$subject = "Contact Us";
// // Email Template
$message .= "<b>Message : </b>".$_POST['name']."<br>";
$message .= "<b>Email Address : </b>".$_POST['email']."<br>";
$message .= "<b>Message : </b>".$_POST['message']."<br>";
$header = "From:".$_POST['email']." \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
// // message Notification
if( $retval == true ) {
echo json_encode(array(
'success'=> true,
'message' => 'Message sent successfully'
));
}else {
echo json_encode(array(
'error'=> true,
'message' => 'Error sending message'
));
}
?>
I tried various DataTypes and ContentForms.
At least headers: { "Content-Type": "multipart/x-www-form-urlencoded" },
I wonder why content type in request header is not changing. I see this in the Browser under Network. It's application/json all time. But I don't know if it's an important fact.

Trying to figure out how to interface with the PayGate API

I can see that these are the parameters required when I make a call to the payment gateway API, but I have no idea how I would implement this in Javascript (specifically React). Any translators able to lend a hand?
Here is the example code in PHP:
$encryptionKey = 'secret';
$DateTime = new DateTime();
$data = array(
'PAYGATE_ID' => 10011072130,
'REFERENCE' => 'pgtest_123456789',
'AMOUNT' => 3299,
'CURRENCY' => 'ZAR',
'RETURN_URL' => 'https://my.return.url/page',
'TRANSACTION_DATE' => $DateTime->format('Y-m-d H:i:s'),
'LOCALE' => 'en-za',
'COUNTRY' => 'ZAF',
'EMAIL' => 'customer#paygate.co.za',
);
$checksum = md5(implode('', $data) . $encryptionKey);
$data['CHECKSUM'] = $checksum;
$fieldsString = http_build_query($data);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, 'https://secure.paygate.co.za/payweb3/initiate.trans');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['HTTP_HOST']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldsString);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
I have been trying to use axios to make the request, but any method will do. I was trying to create an axios instance like so:
export default axios.create({
baseURL: 'https://secure.paygate.co.za/payweb3/initiate.trans',
headers:{
//I guess this is where PAYGATE_ID etc would go, but I'm not sure how to format it
}
})```
For React, the way to handle this is to generate an MD5 checksum and append it to the payload before sending, probably using CryptoJS or something. I created this function to generate the MD5:
const generateMD5 = (obj, secret = 'paygateSecret') => {
let str = ''
for (let val in obj){
str += obj[val]
}
str += secret
return CryptoJS.MD5(str).toString()
}
I have an object that contains my data:
var data = {
PAYGATE_ID: 10011072130,
REFERENCE: ref,
AMOUNT: amount,
CURRENCY: 'ZAR',
RETURN_URL: window.location.href,
TRANSACTION_DATE: new Date().toISOString(),
LOCALE: 'en-za',
COUNTRY: 'ZAF',
EMAIL: email,
}
Please note the order. It is very important.
Then, I generate the checksum using:
const CHECKSUM = generateMD5(data)
And then make the axios call:
axios.post('https://secure.paygate.co.za/payweb3/initiate.trans', { ...data, CHECKSUM }).then(...).catch(...)
I think this should work!

Sending JSON HTTP request using Guzzle HTTP: Result parameters are not as expected

I want to send a JSON request to an endpoint but the results that I get don't match the parameters requested.
This is the array
$datas = [
"institutionCode" => $institutionCode,
"brivaNo" => $brivaNo,
"custCode" => $custCode
];
This is the response using Guzzle HTTP
try {
$response = $client->request($verb, $endpoint,
[
"headers" =>
[
"Authorization" => "Bearer " . $token,
"BRI-Timestamp" => $timestamp,
"BRI-Signature" => $signature,
],
"json" => $datas
]
);
return $response;
}
catch (\GuzzleHttp\Exception\RequestException $e) {
return $e->getResponse();
}
This is the response from the endpoint
{
"status": false,
"errDesc": "Institution Code Tidak Boleh Kosong",
"responseCode": "03",
"data": {
"{\"institutionCode\":\"J104408\",\"brivaNo\":\"77777\",\"custCode\":\"7878787878\"}": ""
}
}
Why does the "data" not match the data array I have given above and instead creates a new pattern with a backslash in it?
This is the native way using cURL PHP
if there is someone can turn it into a Guzzle Http, it will help me,
after I tried this code, it also didn't help at all
$institutionCode = "J104408";
$brivaNo = "77777";
$custCode = "123456789115";
$payload = "institutionCode=".$institutionCode."&brivaNo=".$brivaNo."&custCode=".$custCode;
$path = "/v1/briva";
$verb = "DELETE";
$base64sign = generateSignature($path,$verb,$token,$timestamp,$payload,$secret);
$request_headers = array(
"Authorization:Bearer " . $token,
"BRI-Timestamp:" . $timestamp,
"BRI-Signature:" . $base64sign,
);
$urlPost ="https://sandbox.partner.api.bri.co.id/v1/briva";
$chPost = curl_init();
curl_setopt($chPost, CURLOPT_URL,$urlPost);
curl_setopt($chPost, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($chPost, CURLOPT_POSTFIELDS, $payload);
curl_setopt($chPost, CURLINFO_HEADER_OUT, true);
curl_setopt($chPost, CURLOPT_RETURNTRANSFER, true);
$resultPost = curl_exec($chPost);
$httpCodePost = curl_getinfo($chPost, CURLINFO_HTTP_CODE);
curl_close($chPost);
$jsonPost = json_decode($resultPost, true);
return $jsonPost;

checking database and validate form with angular

I can use ajax to check infomation in database with jquery but I dont know do same with angularjs . I use
$http({
type : "post",
dataType : "JSON",
url : "register.php",
data : data,
success : function(result)
{
....
}
php code
$errors = array(
'error' => 0
);
$username = $_POST['username']
$password = $_POST['password']
$email =$_POST['email']
$fullname = $_POST['fullname']
$sql = "SELECT * "
. "FROM USERS "
. "WHERE username='".$username."' "
. "OR email='".$email."'";
if (mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
if ($row['username'] == $username){
$errors['username'] = 'Tên đăng nhập đã tồn tại';
}
if ($row['email'] == $email){
$errors['email'] = 'Email đã tồn tại';
}
}
if (count($errors) > 1){
$errors['error'] = 1;
die (json_encode($errors));
}else{
//insert database
}
$result = mysqli_query($conn, $sql);
but I dont know do next step . I want check in database if have user name show message error else show succes .Pls help me
Using success is deprecated but you're on the right path. Here's how you would do it now:
$http({
type : "post",
url : "register.php",
data : data
}).then(function(response){
// If data is returned, do stuff with it here
console.log('Yay, my data was POSTed', response.data);
}, function(response){
console.log('Aww, it failed.');
});
It would be easier to help you further, if you add a bit more information on what you're actually trying to achieve. For instance what is returned by this "register.php" endpoint, and what you intent to do after this.
check the DOC for $http.
The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise.
The response comes under promise (.then).
$http({
type : "POST",
url : "register.php",
data : data,
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available/success
console.log(response.data)
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log(response.data)
});

How to pass data into a Listener when using Guzzle?

I am using Guzzle 3.8.1 with CakePHP 2.5.6 and I am making a call to the Box API. I would like to be able to refresh my access token when it expires. The issue I am encountering is that I may be using any one of N possible access tokens and I want to be able to use the $account_id that is in scope for the function I am defining this in. I don't see how I can pass it into the Listener defined function, since I am not calling that myself. I do see that the expired access_token exists in the $event variable, but I would have to locate it and then parse it from the header that I am passing to Box. I think I could add a custom header containing the account_id, but that seems like a bad way to approach the problem. Can I somehow specify a variable in the request that wouldn't be added as part of the call to Box? Any suggestions are much appreciated, thanks!
`
public function get_folder_list ($account_id = null, $parent_folder_id = null) {
// Get account
$this->Account = ClassRegistry::init('Account');
$account = $this->Account->findById($account_id);
$this->Account->log($account);
// If account doesn't exist, throw error
if(empty($account)) {
throw new NotFoundException(__('Account id not found: ' . $account_id));
}
// Call Box for folder list
$box_url = "https://api.box.com/2.0/folders/";
if (empty($parent_folder_id)) {
$box_url .= "0";
} else {
$box_url .= $parent_folder_id;
}
$this->Account->log($box_url);
$bearer = 'Bearer ' . $account['Account']['access_token'];
$client = new Guzzle\Http\Client();
$client->getEventDispatcher()->addListener('request.error', function(Event $event) {
if ($event['response']->getStatusCode() == 401) {
$Account = new Account;
$Account->log($event);
$Box = new BoxLib;
$account = $Box->refresh_token($account_id);
$bearer = 'Bearer ' . $account['Account']['access_token'];
$request = $client->get($box_url, array('Authorization' => $bearer));
$event['response'] = $newResponse;
$event->stopPropagation();
}
});
$request = $client->get($box_url, array('Authorization' => $bearer));
try {
$response = $request->send();
} catch (Guzzle\Http\Exception\BadResponseException $e) {
// HTTP codes 4xx and 5xx throw BadResponseException
$this->Account->log('Service exception!');
$this->Account->log('Uh oh! ' . $e->getMessage());
$this->Account->log('HTTP request URL: ' . $e->getRequest()->getUrl() . "\n");
$this->Account->log('HTTP request: ' . $e->getRequest() . "\n");
$this->Account->log('HTTP response status: ' . $e->getResponse()->getStatusCode() . "\n");
$this->Account->log('HTTP response: ' . $e->getResponse() . "\n");
}
$this->Account->log($response->json());
$json = $response->json();
$folder_list = array();
foreach ($json['item_collection']['entries'] as $folder) {
$folder_list[$folder['id']] = $folder['name'];
}
//$this->Account->log($folder_list);
return $folder_list;
}
`

Resources