How to send SMS in php API without json response? - php

I am using following code to send SMS in php API.
$ch = curl_init("http://wpsms.whitepearldemo.biz....?user=".$user."&password=".$password."&msisdn=".$msisdn."&sid=".$sid."&msg=".$msg."&fl=".$fl."&gwid=".$gwid);
$result = curl_exec($ch);
curl_close($ch);
Including this response, I also have another response. So it looks like
{
//SMS default response
{"ErrorCode":"000","ErrorMessage":"Success","JobId":"381a80-157cc2142bfa","MessageData":[{"MobileNumber":"919898xxxxxx ","MessageParts":[{"MessageId": "919898xxxxxx -67e3765cdf034f438","MessagePartId":1,"MessageText":"test message"}]}]}
}{
//another response
...
}
When this api called, everything worked properly but app this error -
"onFailer: JSON document was not fully consumed."
.
If I comment SMS code temporarily, no error occurs.
Can we avoid the response of SMS?
Please help me to fix it.

Let me answer my question...Use following code to send SMS without JSON response.
$data = array(
'user' => $user,
'password' => $password,
'msisdn' => $msisdn,
'sid' => $sid,
'gwid' => $gwid,
'fl' => $fl,
'msg' => 'Hi'
);
$curl = curl_init('http://wpsms.whitepearldemo......?format=xml');
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
curl_close($curl);
Thanks & regards.

Related

Plaid API Error "body could not be parsed as JSON" when creating a link token request

I am receiving a "INVALID_BODY" error with the message "body could not be parsed as JSON" when sending a curl request through php to create a plaid link token.
I have the header and body formatted this way:
$ch=curl_init("https://development.plaid.com/link/token/create");
$username = array(
"client_user_id"=>"cus_L7tpXAO0PXsPsh"
);
$headers = array(
'Content-type: application/json'
);
$data = array(
'client_id'=>'ID',
'secret'=>'SECRET',
'client_name'=>'Plaid App',
'user'=>$username,
'products'=>'auth',
'country_codes'=>'US',
'language'=>'en',
'webhook'=>'https://webhook.sample.com'
);
$hstring = http_build_query($headers);
$string = http_build_query($data);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$token = curl_exec($ch);
echo $token;
$return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
?>
There is probably a very obvious formatting issue but I can't see it as is. Appreciate any suggestions or criticisms.
I should also mention building out the POST in Postman also gives invalid body error.
I was getting the same error, but for a different reason. The problem in your code is how you are sending your country codes and products. They are expected to be arrays of strings despite the documentation seeming to say otherwise. Also, I don't think you're sending the data in JSON either... Try this:
$data =[
"client_id" => $plaidID,
"secret" => $plaidSecret,
"client_name" => $clientName,
"user" => [
"client_user_id" => $userID
],
"products" => ["auth"],
"country_codes"=>["US"],
"language" => "en"
];
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"https://".$apiMode.".plaid.com/link/token/create");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch,CURLOPT_HTTPHEADER,["content-type: application/json"]);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode((object)$data,JSON_HEX_APOS | JSON_HEX_QUOT ));
$response = curl_exec($ch);

Always get 404 error when adding ecommerce orders using Mailchimp API 3.0

We're updating our Mailchimp implementation from 1.3 to 3.0. We succesfully updated our code to subscribe someone to a list. Now we're trying to add an ecommerce order. In API v1.3 we did this with the function campaignEcommOrderAdd. I found the function to this with in v3.0: /ecommerce/stores/{store_id}/orders(website link).
But I can't get it to work. When posting to Mailchimp I get an 404 error, but I don't know what I'm doing wrong. Below is my code.
$apiKey = "xxx"; //xxx for privacy reasons
$json = json_encode(array(
'id' => $mailchimp_order['id'],
'customer' => array(
'id' => $mailchimp_order['email_id'],
),
'campaign_id' => $mailchimp_order['campaign_id'],
'currency_code' => "EUR",
'order_total' => $mailchimp_order['total'],
'tax_total' => $mailchimp_order['tax'],
'lines' => $mailchimp_order['items'],
));
$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
$url = 'https://'.$dataCenter.'.api.mailchimp.com/3.0/ecommerce/stores/'.$mailchimp_order['store_id'].'/orders';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
This is the output of my $json var:
{
"id":"10000003",
"customer":{
"id":"a90f52f710"
},
"campaign_id":"641657",
"currency_code":"EUR",
"order_total":"56.90",
"tax_total":"47.02",
"lines":[
{
"id":"224",
"product_id":"4427",
"product_title":"Product name",
"product_variant_id":0,
"quantity":"1",
"price":"49.95"
}
]
}
And this is the error I get:
object(stdClass) {
type => 'http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/'
title => 'Resource Not Found'
status => (int) 404
detail => 'The requested resource could not be found.'
instance => ''
}
Without knowing more I would try a few things here. One (you may have already tried this, but check the output of $url) to make sure that all that is getting set correctly. Secondly I would make sure that the store instance you are posting this order to is reachable/exists by making a GET request to, what would be:
$url = 'https://'.$dataCenter.'.api.mailchimp.com/3.0/ecommerce/stores/'.$mailchimp_order['store_id']'
Lastly I would verify that both the campaign and product instances associated with the order are reachable using:
GET https://{dc}.api.mailchimp.com/3.0/campaigns/641657
GET https://{dc}.api.mailchimp.com/3.0/ecommerce/stores/{store_id}/products/4427
Also if you are doing a lot of updating to 3.0 for your app it might be useful to implement a library that abstracts out a lot of this code I use this one:
https://github.com/Jhut89/Mailchimp-API-3.0-PHP
My reputation score wont let me post more links to those endpoints but they should be easily found in the MailChimp documentation. Hope that helps out.

PHP - Stripe Connect return null

I'm starting with Stripe Payment and need to connect the user to my Stripe app. I follow the guildance in Stripe to get the accesss_token with the PHP code:
// See full code example here: https://gist.github.com/3507366
if (isset($_GET['code'])) { // Redirect w/ code
$code = $_GET['code'];
$token_request_body = array(
'grant_type' => 'authorization_code',
'client_id' => 'ca_*************************',
'code' => $code,
'client_secret' => 'sk_test_************************'
);
$req = curl_init(TOKEN_URI);
curl_setopt($req, CURLOPT_RETURNTRANSFER, true);
curl_setopt($req, CURLOPT_POST, true );
curl_setopt($req, CURLOPT_POSTFIELDS, http_build_query($token_request_body));
// TODO: Additional error handling
$respCode = curl_getinfo($req, CURLINFO_HTTP_CODE);
$resp = json_decode(curl_exec($req), true);
curl_close($req);
echo $resp['access_token'];
} else if (isset($_GET['error'])) { // Error
echo $_GET['error_description'];
} else { // Show OAuth link
$authorize_request_body = array(
'response_type' => 'code',
'scope' => 'read_write',
'client_id' => 'ca_************************'
);
$url = AUTHORIZE_URI . '?' . http_build_query($authorize_request_body);
echo "<a href='$url'>Connect with Stripe</a>";
}
But the response from Stripe is always null. Has anyone experienced the same problem like this before. Any help would be very valuable for me this time.
Thank you very much.
After a while of debugging, I found out the problem is with the cURL library of my PHP server. It seem cURL not work with HTTPS. And base on this thread: PHP cURL Not Working with HTTPS
I find the solution to make it run by bypassing the verification:
...
curl_setopt($req, CURLOPT_POSTFIELDS, http_build_query($token_request_body));
curl_setopt($req, CURLOPT_SSL_VERIFYPEER, false); // Bypass the verification
$resp = json_decode(curl_exec($req), true); // Now has response well.
...
P/s: This is not a good solution, better do more research (here)
I hope this help some beginner like me :)

Incorrect Parameters Sent to Service in POST JSON using cURL

Im making this API adapter to POST data our OMS (Order Management System). And I keep getting this error. I dunno if it's really an error because the adapter is connected. the POSTing is the problem. I'm using JSON and cURL to pass data to be updated. So here's my code:
$data = array(
'package' => array(
'tracking_number' => '735897086',
'package_status' => 'failed',
'failed_reason' => 'other1',
'update_at' => '2013-11-22 09:58:39'
)
);
and this is how I POST it.
$postdata = "apikey=$apikey&method=$method&data=$check";
$ch = curl_init();
//SSL verification fixed with this two codes
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt_array(
$ch,
array(
CURLOPT_URL => $url.'/webservice/',
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_VERBOSE => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $postdata,
CURLOPT_HTTPHEADER => array('Content-type: application/x-www-form-urlencoded')
)
);
$result = curl_exec($ch);
and this is my code to test the connection and check if the POSTing is success.
if(curl_exec($ch) === false) { echo 'Curl error: ' . curl_error($ch); } else { echo 'Operation completed without any errors'; }
$result = curl_exec($ch);
echo $result;
curl_close($ch);
I don't really know why I keep getting the "INCORRECT PARAMETERS SENT TO SERVICE". I already reviewed the documentation, the parameters are right. :(
I do believe it is because your POST variables are an array within an array so, what you end up trying to do with your current approach is invalid as stated.
Prior to setting $data in CURL try running the following:
$data = http_build_query($data);
See the PHP definition of http_build_query for more details
I forgot to add this. I encode it to JSON that's why I use arrays.
$check=json_encode($data);
echo $check;
$postdata = "method=$method&data=$check&apikey=$apikey";
$ch = curl_init();
I echo it first before getting the response to check if it's encoded in JSON. then I got this error:
{"package":{"order_number":"200118788","package_number":"200118788-4274","tracking_number":"735897086","package_status":"failed","failed_reason":"other1","update_at":"2013-08-06 17:02:14"}}Operation completed without any errors{"OmsSuccessResponse":false,"message":"Incorrect parameters sent to service","package_status":null}

Sending Data Using Post Method Without Form

I want to send data to an API. The data include simple variables: username, password, email, etc.
The problem is that O want to send data to this using POST method. I searched this issue on Google, and everyone is saying to go for CURL.
What is CURL? Is it a function, script, API or what?
Is there any other way to do it?
I want to send something like this:
$username, $password to www.abc.com?username=$username&password=$password
Best Regards
By using this function you can send a post request with an optional number of
parameters. Just fill in the postdata array with key values pairs.
Example usage are provided.
<?php
function do_post_request($url, $postdata)
{
$content = "";
// Add post data to request.
foreach($postdata as $key => $value)
{
$content .= "{$key}={$value}&";
}
$params = array('http' => array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $content
));
$ctx = stream_context_create($params);
$fp = fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Connection problem, {$php_errormsg}");
}
$response = #stream_get_contents($fp);
if ($response === false) {
throw new Exception("Response error, {$php_errormsg}");
}
return $response;
}
// Post variables.
$postdata = array(
'username' => 'value1',
'password' => 'value2',
'param3' => 'value3'
);
do_post_request("http://www.example.com", $postdata);
?>
Simply use: file_get_contents()
// building array of variables
$content = http_build_query(array(
'username' => 'value',
'password' => 'value'
));
// creating the context change POST to GET if that is relevant
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'content' => $content, )));
$result = file_get_contents('http://www.example.com', null, $context);
//dumping the reuslt
var_dump($result);
cURL is a library "that allows you to connect and communicate to many different types of servers with many different types of protocols". So you can use cURL to send an HTTP POST request. Please read the PHP manual for detailed information: http://www.php.net/manual/en/book.curl.php
But cURL is not the only answer. You can use PHP Streams, or even connect to the webserver using socket functions and then generate your requests.
Personally I often use cURL because it's very flexible and you can work with cookies easily.
Php curl manual is a good starting point.
Following is an example of the usage of curl in php on Stackoverflow:
Send json post using php
The data set in an xml file:
$post="<?xml version="1.0\" encoding=\"UTF-8\"?>
<message xmlns=\"url\" >
<username>".$username."</username>
<password>".$password."</password>
<status date=\"2010-11-05 14:44:10+02\"/>
<body content-type=\"text/plain\">Noobligatory text</body>
</message>";
$url = "a-url-to-send-the-data";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 6);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close($ch);

Categories