Mock Curl response for testing in laravel - laravel

I am trying to unit test a function(updateMeeting) in laravel which uses a curl request inside it. I tried many google links but nothing worked. can you guys give me suggestions on this matter.
following are relevant methods. $this->meeting is a MeetingModel
public function updateMeeting($meetingId){
$meeting = $this->meeting->find($meetingId);
$endpoint = \Config::get('api_backend_endpoint');
$response = $this->curlPut($endpoint);
if ($response->http_status_code != 200) {
if(Input::get('source') == 'ajax') {
$apiResponse = app(ApiResponse::class);
$message = 'ERROR Updating Meeting ' . $meeting->name;
return $apiResponse->failed($message);
}
return Redirect::route('meetings.show', $meetingId)
->withInput()
->with('message', 'An error occurred hiding meeting with message: ' . $response->errors);
}
$meeting->save();
}
following is curlPut method
private function curlPut($url, $payload = array())
{
$data_string = json_encode($payload);
$ch = curl_init();
//send through our payload as post fields
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->password);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$buffer = json_decode(curl_exec($ch));
curl_close($ch);
return $buffer;
}

Use a webservice like https://www.mocky.io/. Instead of requesting the real API, you send your requests to their API. You can create mock endpoints which return a response you can define.

Related

ngenius-payment not able inegrate, i followed by DOCS but giving me error. It should go to payment page of

public function payment(Request $request){
//===============Getting Access Token from N-Genius Platform Network===============================================
$apikey = "api-key"; // enter your API key here
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api-gateway.sandbox.ngenius-payments.com/identity/auth/access-token");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"accept: application/vnd.ni-identity.v1+json",
"authorization: Basic ".$apikey,
"content-type: application/vnd.ni-identity.v1+json"
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"realmName\":\"ni\"}");
$output = json_decode(curl_exec($ch));
$access_token = $output->access_token;
//===============END Getting Access Token from N-Genius Platform Network=============================================
//===============N-Genius Payment Gateway will redirect to the pay page =============================================
$postData = new StdClass();
$postData->action = 'Sale';
$postData->amount = new StdClass();
$postData->amount->currencyCode = 'AED';
$postData->amount->value = 1 * 100;
$postData->language = 'en';
$postData->emailAddress = 'form user email';
$postData->billingAddress['firstName'] = 'form first name';
$postData->billingAddress['lastName'] = 'form last name;
$postData->merchantAttributes['redirectUrl'] = 'redirection page route';
$token = $access_token;
$json = json_encode($postData);
$outlet = "outlet-id";
$token = $access_token;
$json = json_encode($postData);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api-gateway.sandbox.ngenius-payments.com/transactions/outlets/'.$outlet.'/orders');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$token,
'Content-Type: application/vnd.ni-payment.v2+json',
'Accept: application/vnd.ni-payment.v2+json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$output = json_decode(curl_exec($ch));
$order_reference = $output->reference;
$order_paypage_url = $output->_links->payment->href;
header("Location: ".$order_paypage_url); // execute redirect
//die();
curl_close ($ch);
//===============END N-Genius Payment Gateway will redirect to the pay page =============================================
}
Anyone can help me Please. Please Guide me How to integrate ngenius-payment gateway to laravel app Their documentation not enough to integrate with laravel. i am planing to choose with making payments from their websites, and return back to us with a return URL.
did you get the accessToken?
if yes then try with this post data
{
"action": "SALE",
"amount": {
"currencyCode": "AED",
"value": 1700
},
"merchantAttributes" : {
"redirectUrl" : "url",
"skipConfirmationPage": true,
"cancelText": "Go to Homepage"
},
"emailAddress": "test11#order.com",
"merchantOrderReference": "test-12"
}

I'm trying to track delivery status of a message using php( REST api) from Clickatell

In my controller i have
public function msgStatus(){
$this->load->library('clickatell_rest');
$this->clickatell_rest->getMsgStatus();
}
clickatell rest library class
public function getMsgStatus(){
$msgId = "message ID here";
$authToken = urlencode("token here");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.clickatell.com/rest/message/$msgId");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"X-Version: 1",
"Accept: application/json",
"Authorization: Bearer $authToken"
));
$result = curl_exec ($ch);
print_r($result); exit();
return $result;
}`
when i execute the code the following error displays though my credentials are correct
{"error":{"code":"001","description":"Authentication
failed","documentation":"http://www.clickatell.com/help/apidocs/error/001.htm"}}
i expect my code to return a message status (i.e if the message is queued, failed,delivered to recepient, etc)

POST requests require a Content-length header in laravel

$output = Curl::httpGet("https://bhleh.com/emailstorage", "POST", $params);
return $output;
this is in my laravel but when ever i try to run this i get an error saying
411. That’s an error.
POST requests require a Content-length header. That’s all we know.
i tried adding header files in my middle ware folder but nothing seems to work.
i figured out that the Content-length header isn't included in laravel (i think so not so sure) so how would i add it
please note i am very new to laravel
this fix to this is that this i replaced the whole code with this
$data_string = json_encode($params);
$ch = curl_init('https://bhleh.com/emailstorage');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
return $result;
I was facing the same issue but I was not sending CURLOPT_POSTFIELDS as per the API endpoint. I don't need to send any variable but when I send CURLOPT_POSTFIELDS with a blank array it started working.
$data_string = array();
$ch = curl_init('https://bhleh.com/emailstorage');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data_string));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
);
$result = curl_exec($ch);
return $result;

Quick q. Mailchimp API 3.0

Can i use the first script or i need to use the curl option for mailchimp 3.0? I read some posts that the first one may be depreciated.. is that correct? Note that i'm not running on WordPress. Thank you for your fast answers.
<?php
require("vendor/autoload.php");
use \DrewM\MailChimp\MailChimp;
$mc = new MailChimp('apikey');
$email = $_POST['email'];
$subscriber_hash = $mc->subscriberHash($email);
$response = [];
$list_id = 'listid';
$resp = $mc->get("/lists/$list_id/members/$subscriber_hash";
if ($mc->success()) {
$response['message'] = 'Thank you for subscribing to the mailing list';
// User successfully subscribed - set HTTP status code to 200
http_response_code(200);
} else {
$response['message'] = $mc->getLastError();
// User not subscribed - set HTTP status code to 400
http_response_code(400);
}
// Return json-formatted response
echo json_encode($response);
?>
Or should i use this one?
function mc_checklist($email, $debug, $apikey, $listid, $server) {
$userid = md5($email);
$auth = base64_encode( 'user:'. $apikey );
$data = array(
'apikey' => $apikey,
'email_address' => $email
);
$json_data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://'.$server.'.api.mailchimp.com/3.0/lists/'.$listid.'/members/' . $userid);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '. $auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = curl_exec($ch);
if ($debug) {
var_dump($result);
}
$json = json_decode($result);
echo $json->{'status'};
}
This row is only for stackoverflow not alowing me to post that much code without including more details.
The first is not deprecated. It uses this wrapper to make API calls using the same API version that the second block of code uses. It's just simpler to work with so you don't have to write separate CURL requests for every call. You can also take a look at some of its source code and notice that it uses CURL anyway to make its calls.
So either way will use CURL, and whichever option you choose is simply a matter of preference.
Hopefully that clears it up for you!

How to upload image from one domain to another?

I have two domain one is stgportal and another is stg.I want to upload image from stgportal to stg.My code is given below
move_uploaded_file($_FILES['ThumbnailImage']['tmp_name'],"http://stg.eminencesystem.com/assets/images/th/".$thimg)
show the error: failed to open stream: HTTP wrapper does not support writeable connections
how can i resolve this issue?
You can use CURL to send file to another server securely like this
At stgportal side
function sendImageToServer($path = "", $file = null)
{
$post_url = "http://stg.eminencesystem.com/post_file";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $post_url);
//most importent curl assues #filed as file field
$post_array = array(
"folder_name" => $path
);
if ((version_compare(PHP_VERSION, '5.5') >= 0)) {
$post_array['file'] = new CURLFile($file);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, TRUE);
} else {
$post_array['file'] = "#" . $file;
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_array);
$response = curl_exec($ch);
return $response;
}
At stg side
$ImagePath = "/var/www/html/assets/";
$files = $_FILES;
$folder_name = utf8_decode($_POST['folder_name']);
$savepath = $ImagePath . $folder_name . $files['name'];
copy($file['tmp_name'], $savepath);
echo 1;
exit;

Resources