Convert PHP http post request to Livecode - php

I am new to Livecode and I have tried couple of things to convert this php http post request code to Livecode but not working. Will need it either with cURL or without cURL.
$receive_momo_request = array(
'CustomerName' => 'Customer Name',
'CustomerMsisdn'=> '054XXXX',
'CustomerEmail'=> 'customer#gmail.com',
'Channel'=> 'mtn-gh',
'Amount'=> 0.8,
'PrimaryCallbackUrl'=> 'http://requestb.in/1minotz1',
'Description'=> 'T Shirt',
);
//API Keys
$clientId = 'xxxxxxx';
$clientSecret = 'xxxxxxx';
$basic_auth_key = 'Basic ' . base64_encode($clientId . ':' . $clientSecret);
$request_url = 'https://api.hubtel.com/v1/merchantaccount/merchants/HMXXXXXXX/receive/mobilemoney';
$receive_momo_request = json_encode($receive_momo_request);
$ch = curl_init($request_url);
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $receive_momo_request);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
'Authorization: '.$basic_auth_key,
'Cache-Control: no-cache',
'Content-Type: application/json',
));
$result = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
if($err){
echo $err;
}else{
echo $result;
}
This is what I have done so far may be am missing something.
on mouseUp
global gFirstName, gLastName
put gFirstName & " " & gLastName into lFullName
put lFullName into tArray[ "CustomerName"]
put "gPhoneNumber" into tArray["CustomerMsisdn"]
put "gEmail" into tArray["CustomerEmail"]
put "airtel-gh" into tArray["Channel"]
put "0.01" into tArray["Amount"]
put "http://requestb.in/1minotz1" into tArray["PrimaryCallbackUrl"]
put "FBMC Mobile" into tArray["Description"]
put true into tArray ["FeesOnCustomer"]
put ArrayToJSON(tArray) into receive_momo_request
put "ABCD" into clientId
put "1234" into clientSecret
set the httpHeaders to "Content-type: application/json" && "Authorization: Basic " && base64Encode("clientId:clientSecret") && "Cache-Control: no-cache"
post receive_momo_request to url "https://api.hubtel.com/v1/merchantaccount/merchants/HMXXXXXXX/receive/mobilemoney"
end mouseUp

Your LiveCode code looks good on first glance. I would try two things:
First, URLencode the data you are posting before you post it.
put ArrayToJSON(tArray) into receive_momo_request
put urlEncode(receive_momo_request) into receive_momo_request
Second, after the post command, check the itvariable to see what data was returned by the web server. You can also check the result to see if an error occurred.
post receive_momo_request to url "https://api.hubtel.com/v1/merchantaccount/merchants/HMXXXXXXX/receive/mobilemoney"
put it into tServerFeedback
answer the result
This should at least tell you what is happening after you issue the post command.

Related

How to get access token using refresh token in DocuSign and PHP?

I want to update my access token using the previous refresh token in DocuSign? I am getting
{
"error": "invalid_grant",
"error_description": "unsupported_grant_type"
}
Below is how I made the request.
$client_id = env('DOCUSIGN_CLIENT_ID');
$client_secret = env('DOCUSIGN_CLIENT_SECRET');
$encoded_client_id = utf8_decode(base64_encode($client_id));
$encoded_client_secret = utf8_decode(base64_encode($client_secret));
$integrator_and_secret_key = "Basic " . "{$encoded_client_id}:{$encoded_client_secret}";
// $integrator_and_secret_key = "Basic " . utf8_decode(base64_encode("{$client_id}:{$client_secret}"));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://account-d.docusign.com/oauth/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$data = array(
'refresh_token' => "My refresh token from previous successful request",
'grant_type' => 'refresh_token',
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$headers = array();
$headers[] = "Authorization: Basic " . "{$encoded_client_id}:{$encoded_client_secret}";
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$headers[] = 'Cache-Control: no-cache';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
Log::info($result);
So, not confident that's the only issue, but the way you encode the clientId and clientSecret is different, you encode each part separately, instead of the whole thing with the colon.
https://www.docusign.com/blog/developers/authorization-code-grant-refresh-tokens shows that it's done like this:
string codeAuth = (clientId ?? "") + ":" + (clientSecret ?? "");
byte[] codeAuthBytes = Encoding.UTF8.GetBytes(codeAuth);
string codeAuthBase64 = Convert.ToBase64String(codeAuthBytes);
Note that the string that's encoded already had them combined, not each of them encoded separately.
Now, the error can also be because the Integration Key (IK or clientID) is not configured correctly, you use a bad refreshToken, it expired, you use the wrong environment (developer vs. production) and maybe a couple more reasons I forgot. Need to triple check all the values to ensure this if still not working.
For those who stuck on this issue:
The solution was just to change the content-type from application/x-www-form-urlencoded to application/json

CentralPlanner API cal via curl. 500 response

I have done little with cURL so far, so bear with me.
This is the api that I am currently dealing with:
CentralPlannerAPI
I have a token, I can call it via the bash shell and all is fine, except for the part where PHP comes into play. I constantly get authentication errors. The last one would be a 500.
This one works:
curl "https://centralplanner.net/api/contacts" -H 'Authorization: Token token="my-api-token"'
This one does not work:
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, "https://centralplanner.net/api/contacts/count" );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array( "Authorization: Token token='myToken'" ) );
curl_exec( $ch );
curl_close( $ch );
Why does the PHP part not work?
What am I not getting here. Yes, there is currently not much to it and later one it will only be slightly more than this, at least from the current perspective; no it will not run on a server; yes, I will add some validation on and yes, it will a proper class construct and so and so forth.
PS:
Before someone refers me to other SO sites, I looked at them ... did not help.
Please try this code:
$ch = curl_init("https://centralplanner.net/api/contacts/count");
$options = [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => "Authorization: Token token=\"myToken\""
];
curl_setopt_array($ch, $options);
$content = curl_exec($ch);

Which is the best and fastest way to send JSON in post request in PHP?

I am android developer and have some knowledge in php. I need to make post request in php. I found two ways to achieve it.
1. Using CURL.
$url = "your url";
$content = json_encode("your data to be sent");
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
2. Using Simple Post(file_get_contents).
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
But, I just want to know which is better and efficient way to do that and why?
Is there any server/browser or any platform related issue any of them?
Or is there any other technique to achieve that?
Suggestions are welcome.Thanks
Best way to achieve is always
Using CURL.
as this is fastest & more reliable..
If you are just sending a JSON reply from a PHP script launched by a call from your Android JAVA code then the simplest and probably the fasted is just to echo the JSON string from your PHP script.
i.e.
<?php
// read the $_POST inputs from Android call
// Process whatever building an array
// or better still an object containing all
// data and statuses you want to return to the
// android JAVA code
echo json_encode($theObjectOrArray);
exit;
This way it is all part of the same post/responce. If you get CURL involved you are breaking the simple life cycle.

Google Cloud Messaging Push Notifications only work once (PHP, Android)

I am having trouble getting Google Cloud Messaging for Android working.
I have had it working before but it decides to stop working after the first couple of times.
In order to get it working again I have to delete my API key and recreate it.
I am using PHP with a SERVER API key with a IP whitelist of ::/0 (All IPv6 apparently)
Note: My android app requests a device message key each time the app is opened (Usually returns the same message key)
The Error I get is: Unauthorized Error 401
When I got to the following url to check my app message id i get 'invalid token'.
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=APA91bHuQEWGsvlRUhlSztNpqLVOZQGZPiGFHjQw2plcF-z8t29zvNNgNoDiRe-CbY9Fb-XcPQAFqJvy4HBfWTrTPPpzcY3pd5vX38WGalOsZ5iDiJeglpafLTC7eFkN4UA9JPKWZ4lqNiGLoH3w8W_GpFAFW5F-kLLzcbrPxwSFqyfUpmM8-14
The PHP code I am using is:
$data = array( 'message' => 'Hello World!222!' );
$ids = array('APA91bHuQEWGsvlRUhlSztNpqLVOZQGZPiGFHjQw2plcF-z8t29zvNNgNoDiRe-CbY9Fb-XcPQAFqJvy4HBfWTrTPPpzcY3pd5vX38WGalOsZ5iDiJeglpafLTC7eFkN4UA9JPKWZ4lqNiGLoH3w8W_GpFAFW5F-kLLzcbrPxwSFqyfUpmM8-14');
$apiKey = 'AIzaSyATkp_UTZh....'; //obviously the complete key is used...
$url = 'https://android.googleapis.com/gcm/send';
$post = array('registration_ids' => $ids, 'data' => $data);
$headers = array( 'Authorization: key=' . $apiKey, 'Content-Type: application/json');
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $post ) );
$result = curl_exec( $ch );
if ( curl_errno( $ch ) )
{
echo 'GCM error: ' . curl_error( $ch );
}
curl_close( $ch );
echo $result;
Thanks for any help given.
EDIT: It seems to work since I unregistered my device and reregistered it with GCM. I am not sure if this is a permanent fix but it works for now.

Passing a parameter in the header (XML RPC)

I'm trying to set up a server status for the MMORPG Champions Online. I got some basic information from the web master and this is all he told me:
XML-RPC call to server: http://www.champions-online.com/xmlrpc.php
function name: wgsLauncher.getServerStatus
Parameter (language): en-US
Now, I found a nice example to start with here, and I ended up with this code:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
# Using the XML-RPC extension to format the XML package
$request = xmlrpc_encode_request("wgsLauncher.getServerStatus", "<param><value><string>en-US</string></value></param>", null );
# Using the cURL extension to send it off,
# first creating a custom header block
$header[] = "Host: http://www.champions-online.com:80/";
$header[] = "Content-type: text/xml";
$header[] = "Content-length: ".strlen($request) . "\r\n";
$header[] = $request;
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, "http://www.champions-online.com/xmlrpc.php"); # URL to post to
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); # return into a variable
curl_setopt( $ch, CURLOPT_HTTPHEADER, $header ); # custom headers, see above
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'POST' ); # This POST is special, and uses its specified Content-type
$result = curl_exec( $ch ); # run!
curl_close($ch);
echo $result;
?>
But I'm getting a "400 Bad Request" error. I'm new to XML RPC and I barely know php, so I'm at a loss. The examples from the php site show how to use an array as a parameter, but nothing else.
I obtained the parameter string <param><value><string>en-US</string></value></param> from this XMLRPC Debugger (very nice btw). I entered the parameter I needed in the "payload" box and this was the output.
So, I would appreciate any help on how to pass this parameter to the header.
Note: My host supports xmlrpc but it seems the function "xmlrpc_client" doesn't exist.
Update: The web master replied with this information, but it's still not working... it's getting to the point I may just scrape the status off the page.
$request = xmlrpc_encode_request("wgsLauncher.getServerStatus", "en-US" );
Ok, I finally figured out my answer... It seemed to be a problem in the header, because it worked when I changed the cURL code to match the code I found it on this site. The post is about how to remotely post to wordpress using XMLRPC in php.
This is the code I ended up with:
<?php
// ini_set('display_errors', 1);
// error_reporting(E_ALL);
# Using the XML-RPC extension to format the XML package
$request = xmlrpc_encode_request( "wgsLauncher.getServerStatus", "en-US" );
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, "http://www.champions-online.com/xmlrpc.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$result = curl_exec($ch);
curl_close($ch);
$method = null;
$params = xmlrpc_decode_request($result, &$method);
# server status result = true (up) or false (down)
$status = ($params['status']) ? 'up' : 'down';
$notice = ($params['notice'] == "") ? "" : "Notice: " + $params['notice'];
echo "Server Status: " . $status . "<br>";
echo $notice;
?>

Categories