How to integrate instamojo payment gateway with codeigniter rest server? - rest

I am trying to integrate Instamojo Payment Gateway within Chris Kacerguis’ REST Server.
Problem:
The below code:
public function instamojotest_post()
{
$api = new Instamojo\Instamojo(‘abcd1234’, ‘efgh5678’, 'https://test.instamojo.com/api/1.1/');
try {
$response = $api->paymentRequestCreate([
'amount' => 100,
'purpose' => 'New Product Purchase',
'buyer_name' => 'Test User',
'email' => 'testuser#gmail.com',
'phone' => '9876543210',
'redirect_url' => 'http://www.example.com/products_api/validate_payment'
]);
header('Location: ' . $response['longurl']);
} catch (Exception $e) {
$this->response([
'success' => false,
'message' => $e->getMessage()
], 500);
}
}
is not redirecting to the Instamojo Payment Site and no error is being displayed.
It is working fine and redirecting successfully with vanilla CodeIgniter.
Questions:
1) Is it, at all, possible to redirect from within a REST Server Post Method?
2) If the above is possible, then what is wrong with my code?
3) Is there any other way to achieve what I am trying to do?
I found many tutorials on the internet but none of them are using REST Server.

I stumbled accross this question while Googling. I was also facing the same issue and here is how I solved it.
Note: This is not exactly a solution but a work-around. Also I admit that this may not be the best solution out there, but it worked for me.
I returned the payment url from the Rest Server, and redirected to the url from within the Rest Client.
Rest Client Code:
class Test extends CI_Controller
{
public function instamojo_make_payment()
{
$url = "http://www.example.com/products_api/instamojotest";
$params = []; //You will obviously be needing this in real life implementation :)
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_POST, 1);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($curl_handle);
curl_close($curl_handle);
if ($response['success'])
header('Location: ' . $response['payment_url']);
else
$this->load->view('payment_failed_page');
}
}
Rest Server Code:
class Products_api extends REST_Controller
{
public function instamojotest_post()
{
$api = new Instamojo\Instamojo('abcd1234', 'efgh5678', 'https://test.instamojo.com/api/1.1/');
try {
$response = $api->paymentRequestCreate([
//Make sure to pass these data from the Rest Client
'amount' => 100,
'purpose' => 'New Product Purchase',
'buyer_name' => 'Test User',
'email' => 'testuser#gmail.com',
'phone' => '9876543210',
'redirect_url' => 'http://www.example.com/products_api/validate_payment'
]);
$this->response([
'success' => true,
'payment_url' => $response['longurl']
], 200);
} catch (Exception $e) {
$this->response([
'success' => false,
'message' => $e->getMessage()
], 500);
}
}
}
While giving this answer I assumed that the Api is open. If it is not, then make sure to pass your credentials when making the curl call.
Update
Thanks to #AshwiniChaudhary's comment below, which states that:
REST APIs are not meant for redirection. REST API returns JSON, XML
etc and the receiver takes care of whatever is supposed to be done.
the actual reason behind the fact, "why REST Server is not letting us to perform the redirect", becomes pretty clear.

Related

Where can I find others callback of infinite grid store?

I use an Infinite Grid, actually all work fine but in the PHP that the store uses I do a request to an external webservice.
This is my Store Load:
myInfGrid.getStore().load({
scope : this,
url : 'download.php',
params : { },
callback: function(records, operation, success) {
if (success) {
// Here a process is done only once time even
// for others automated launched requests
}
}
});
My download.php file contains a curl request to a webservice like below.
Sometimes the WebService takes a very long time to answer.
...
$url = "https://external_webservice";
$params = array('callback' => $callback,
'q' => $query,
'rows' => $rows,
'sort' => $sort,
'start' => $start);
$url .= '?' . http_build_query($params);
$myCurl = curl_init($url);
curl_setopt($myCurl, CURLOPT_RETURNTRANSFER, true);
$fetchResult = curl_exec($myCurl);
curl_close($myCurl);
// HERE my process of $fetchResult content
...
I would like to extract this WebService Curl call and put it only on each callback.
My problem is: I don't know where are others callbacks.
I mean callbacks associated to all requests that are launched automatically by the infinitegrid ?

How to Retrieve HTTP Status Code with Guzzle?

New to Guzzle/Http.
I have a API rest url login that answer with 401 code if not authorized, or 400 if missing values.
I would get the http status code to check if there is some issues, but cannot have only the code (integer or string).
This is my piece of code, I did use instruction here ( http://docs.guzzlephp.org/en/stable/quickstart.html#exceptions )
namespace controllers;
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\ClientException;
$client = new \GuzzleHttp\Client();
$url = $this->getBaseDomain().'/api/v1/login';
try {
$res = $client->request('POST', $url, [
'form_params' => [
'username' => 'abc',
'password' => '123'
]
]);
} catch (ClientException $e) {
//echo Psr7\str($e->getRequest());
echo Psr7\str($e->getResponse());
}
You can use the getStatusCode function.
$response = $client->request('GET', $url);
$statusCode = $response->getStatusCode();
Note: If your URL redirects to some other URL then you need to set false value for allow_redirects property to be able to detect initial status code for parent URL.
// On client creation
$client = new GuzzleHttp\Client([
'allow_redirects' => false
]);
// Using with request function
$client->request('GET', '/url/with/redirect', ['allow_redirects' => false]);
If you want to check status code in catch block, then you need to use $exception->getCode()
More about responses
More about allow_redirects
you can also use this code :
$client = new \GuzzleHttp\Client(['base_uri' 'http://...', 'http_errors' => false]);
hope help you

How to call soap api with BASIC authantication for WSDL URL

Blockquote
We are using Soap API but we can not connect to server.I am new in soap api.
We are using Code
username = testclient
password = tes#123
try {
$client=new SoapClient($wsdl,array('trace' => 1,"stream_context" => $context));
$result = $client->__call('getStatus', array());
} catch (Exception $e) {
echo $e->getMessage();
}
After passing header.
$client = new SoapClient(
'https://test/app/uat/test?wsdl',
array(
"exceptions" => 0,
"trace" => 1,
'stream_context' => stream_context_create(array(
'http' => array( 'header' => 'Authorization: Basic dGVzdGNsaWVudDp0ZXN0QDEyMw==' ),
)),
));
$result = $client->__soapCall('getBalance', array());
Also we have client and secret but How we can use for BASIC auth?
Where we can set user, pass and key and secret.
If you need any thing please let me know.
Thankyou

SOAP Client Request --> Bad Request

I've been asked to look into syncing data using a SOAP service. I don't really know SOAP very well at all and I get a Bad Request Error.
The function I'm trying to call is a test echo function:
public string EchoAuthenticated(string text)
Each time I call it I get an error.
I have commented out the username / password setting as I don't know the username and password right now and my contact person is on leave :( Right now though I'd be perfectly happy just to get an authentication failed message rather than an error...
If anyone could point me in the right direction here please...
Thanks,
John
<?php
$apiUrl = 'https://exdev.api.propctrl.co.za/v3/Integration.svc?wsdl';
$options = array( 'trace' => 1, 'exceptions' => 1, 'soap_version' => SOAP_1_2);
try
{
$client = new SoapClient($apiUrl, $options);
//$data = array(
// 'Username' => "test",
// 'Password' => "test"
//);
//$header = new SoapHeader('https://exdev.api.propctrl.co.za/v3/', 'CredentialsHeader', $data, false);
//$client->__setSoapHeaders($header);
var_dump($client->__getFunctions());
print $client->EchoAuthenticated("Test String");
var_dump($client->__getLastRequest());
}
catch(Exception $e)
{
echo $e->getMessage();
}
?>
You might try something like:
...
$client = new SoapClient($apiUrl, $options);
var_dump($client->__getFunctions());
$auth = array("Username" => "John", "Password" => "secret",
"IsP24Credentials" => false);
$header = new SoapHeader("https://www.propctrl.com/", "CredentialsHeader",
$auth, FALSE);
$client->__setSoapHeaders($header);
print $client->EchoAuthenticated(array(
"text" => "My text to be echoed."
));
var_dump($client->__getLastRequest());
...
This should result in a request SOAP request like this:
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:ns1="https://www.propctrl.com/v3" xmlns:ns2="https://www.propctrl.com/">
<env:Header>
<ns2:CredentialsHeader>
<ns2:IsP24Credentials>false</ns2:IsP24Credentials>
<ns2:Password>secret</ns2:Password>
<ns2:Username>John</ns2:Username>
</ns2:CredentialsHeader>
</env:Header>
<env:Body>
<ns1:EchoAuthenticated>
<ns1:text>My text to be echoed.</ns1:text>
</ns1:EchoAuthenticated>
</env:Body>
</env:Envelope>
As a side note, you might have a look at http://www.soapui.org/. This tool helps greatly with web service development.

SugarCRM REST api error

I am trying to retrieve custom module data through the Sugarcrm REST api but I am not able to do so as I am not even able to login with the documentation code, I tried same thing as given in documentation
<?php
// specify the REST web service to interact with
$url = 'localhost/~jmertic/sugarcrm/service/v4_1/rest.php';
// Open a curl session for making the call
$curl = curl_init($url);
// Tell curl to use HTTP POST
curl_setopt($curl, CURLOPT_POST, true);
// Tell curl not to return headers, but do return the response
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the POST arguments to pass to the Sugar server
$parameters = array(
'user_auth' => array(
'user_name' => 'username',
'password' => md5('password'),
),
);
$json = json_encode($parameters);
$postArgs = array(
'method' => 'login',
'input_type' => 'JSON',
'response_type' => 'JSON',
'rest_data' => $json,
);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($curl);
// Convert the result from JSON format to a PHP array
$result = json_decode($response);
if ( !is_object($result) ) {
die("Error handling result.\n");
}
if ( !isset($result->id) ) {
die("Error: {$result->name} - {$result->description}\n.");
}
// Get the session id
$sessionId = $result->id;
changed the username,password and url to match my setup but i get an error stating
No direct script access allowed
I tried to search this on web but couldnt find any relevant solution.
I am using sugarCRM 6.5.0RC2 version
Regards,
Anand Joshi
You probably has some defense configured on your WEB server which allows you to access only to index.php.
To verify it, try to go from the browser to your API URL: http://YOUR_DOMAIN_NAME/service/v4_1/rest.php
Or/and run from terminal: wget http://YOUR_DOMAIN_NAME/service/v4_1/rest.php
If it shows the same message, check your .httaccess on this folder or/and your web server config file.
If no, how do you run the API test script? through CLI or from browser?
Also I suggest you to use some Open Source SugarCRM REST API Wrapper. I use this one: https://github.com/asakusuma/SugarCRM-REST-API-Wrapper-Class
Shouldn't the line be this...
$url = 'http://yoursugarinstance/service/v4_1/rest.php';