I have this methode :
$oAndroidService = new GoogleGNCService($message);
# divide per batch with 1000 users
$a_batch = array_chunk($a_users, 1000);
for($i = 0; $i < count($a_batch); $i++){
# get the liste of tokens
foreach($a_batch[$i] as $batch){
$a_tokens[] = $batch['token'];
}
# if push sent with success
if($oAndroidService->sendPush($a_tokens)){
foreach($a_batch[$i] as $userToProcess){
// update push token history
}
}
echo 'PUSH SENT !';
# unset the array with tokens
unset($a_tokens);
}else{
echo 'ERROR SENT PUSH'
}
}
And the method that sent pushes :
public function sendPush($a_token){
# init the curl connection
$ch = curl_init();
# if success connection
if($ch){
# array that will be send in post with curl call
$a_post = array(
'registration_ids' => $a_token,
'data' => $this->getMessage(),
);
# set the options of curl request
curl_setopt($ch, CURLOPT_URL, self::ANDROID_URL);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getHeaders());
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($a_post));
# execute the request
$result = curl_exec($ch);
if($result === false){
echo('Curl failed : ' . curl_error($ch));
return false;
}
# close the request
curl_close($ch);
return true;
}
echo 'Connection failed';
return false;
}
I have 2 questions :
If I sent 1000 tokens and curl failed, I need to resend this array with tokens one more time ? If failed the second time, I need to resent third time ?
If curl failed how to know what are the token that poses problems ?
Thx for you help in advance
Related
This is the API provided by https://www.cashmaal.com/api I deposited some cash in my cashmaal account and the transaction id I got whenever I try to verify the payment by transaction id it shows me an error
Error: Error! Transaction Id () is invalid.
$web_id=""; // Your Web ID here (you can found this on cashmaal account where you add site)
if(isset($_POST['CM_TID'])) {
$CM_TID=$_POST['CM_TID']; // getting TID with user redirection
$url="https://www.cashmaal.com/Pay/verify_v2.php?CM_TID=".urlencode($CM_TID)."&web_id=".urlencode($web_id);
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result,true);
if($obj['status'] == 1)
{ // it means payment received....
//response format in JSON
//Example Response
/*
{"status":"1","receiver_account":"8","USD_amount":"1.670","fee_in_USD":"0.000","PKR_amount":"280","fee_in_PKR":"0","USD_amount_with_fee":"1.670","PKR_amount_with_fee":"280","trx_website":"website.com","transaction_id":"2JW9651118P","trx_date":"25-03-2020 9:13:48 PM","order_id":"12345678","addi_info":"Test Payment","sender_details":"Fund Received From 161919","trx_details":"$1.67 Receive against TID: '2JW9651118P'"}
*/
// Verify All things and Confirm user order here
if($obj['USD_amount'] == '2')
{
echo 'we received your payment';
}
else
{
echo "we didn't received the your mentioned payment ";
}
}
else
{
echo "Error:".$obj['error'];
}
}
Just found a solution of this that this cashmaal api verify the transaction id only if the transaction is done by other cashmaal account
I have written a Payment processor.php file to receive parameters from an ecommerce system then post to a PSP (Payment Service Provider), then this Json response from the PSP will be decoded, verified and Keys converted and parsed to the ecommerce system this way:
header("Location: ".$hosturl."orderprocessor?
orderid=$custref&sig=".$_POST['SessionId']);
Before giving out item in cart to users.
$hosturl has been defined as
$hosturl="localhost:8080/ekp/";
in another file
The result I get each time I do cart checkout with "Payment processor.php" file is just a white screen. I am supposed to see the PSP's interface to receive user's card details instead.
The PSP's URL is; " https://developers.paystack.co/reference#paystack-standard-x" I am following the cURL PHP sample for reference.
kindly assist if corrections are spotted in my code.
This is my Payment processor.php file:
<?php require_once 'includes/config.inc.php' ?>
<?php
$parameters = array();
if (isset($_POST['amount'])) { /* came the LMS; about to send data to
Paystack */
$sig=hash_hmac("md5","amount=".urlencode($_POST['amount']).
"¤cy=".urlencode($_POST['currency']).
"&orderid=".urlencode($_POST['orderid']), $KEY);
$parameters['UserName']=$username;
$parameters['Password']=$password;
$parameters['reference']=$_POST['orderid'];
$parameters['Amount']=($_POST['amount'] * 100);
//should change SessionId' to be named reference
$parameters['SessionId']=$sig;
$parameters['SessionKey']=$encryptionKey;
$parameters['DL']="activ_purchase";
$parameters['ServerURL']=
base64_encode("http://localhost/nse/ecommerce/paystack.php");
$parameters['UserURL']=
base64_encode("http://localhost/nse/ecommerce/paystack.php");
$parameters['AccountNumber']=$accountnumber;
//$parameters['UserDeclinedURL']=
base64_encode($hosturl."externalpaymentcancel?
orderid=".$_POST['orderid']);
// print_r($parameters);
$cart=$_POST['cart'];
// var_dump($cart); die;
$cartitems=objectToArray(json_decode($cart));
foreach ( $cartitems['items'] as $item )
{
$productName=$item['description'];
$quantity=1;
$price=$item['price']['amount'];
$parameters['Reference4']=$productName." Qty
".$quantity." # $".$price."\r\n" ;
}
// created parameters for Paystack $postdata here
$postdata = array('email' => 'customer#gmail.com',
'amount' => $parameters['Amount'],
'reference' => $parameters['reference'],
);
//$url = "https://api.paystack.co/transaction/initialize";
//My codes for $ch here
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$paystackUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($postdata)); //Post
Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'Authorization: Bearer sk_test_*****************************',
'Content-Type: application/json'];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec ($ch);
curl_close ($ch);
//My code for $ch ends here
//starting to setup redirect url
if ($result) {
$request = json_decode($result, true);
//print_r($request);
foreach ($request as $input) {
if($input ['data']['reference']){
$sst=['data']['reference'];
break;
}
}
header('Location:'.$result['data']
['authorization_url'].$parameters['SessionId'].$sst);
}
//Use the $result array to get redirect URL paystack
//var_dump($result);
}
else {
$result = array();
$url = 'https://api.paystack.co/transaction/verify/'.$_GET['reference'];
// print_r($parameters);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(
$ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer sk_test_*****************************']
);
$request = curl_exec($ch);
curl_close($ch);
if ($request) {
$result = json_decode($request, true);
// print_r($result);
if($result){
if($result['data']){
//something came in
if($result['data']['status'] == 'success'){
header("Location: ".$hosturl."orderprocessor?
orderid=$reference&sig=".$_POST['SessionId']);
//echo "success";
// the transaction was successful, you can deliver value
/*
# also remember that if this was a card transaction, you can store
the
# card authorization to enable you charge the customer
subsequently.
# The card authorization is in:
# $result['data']['authorization']['authorization_code'];
# PS: Store the authorization with this email address used for this
transaction.
# The authorization will only work with this particular email.
# If the user changes his email on your system, it will be unusable
*/
echo "Transaction was successful";
}else{
// the transaction was not successful, do not deliver value'
// print_r($result); //uncomment this line to inspect the result,
to check why it failed.
echo "Transaction was not successful: Last gateway response was:
".$result['data']['gateway_response'];
}
}else{
echo $result['message'];
}
}else{
//print_r($result);
die("Something went wrong while trying to convert the request variable
to json. Uncomment the print_r command to see what is in the result
variable.");
}
}else{
echo "<html><head><meta http-equiv=\"refresh\"
content=\"5;URL=$hosturl"."externalpaymentcancel?orderid=$custref\">
</head><body style=\"text-align:center; font-family:'Open Sans', Arial,
Helvetica, sans-serif;\"><p><img
src=\"/nd/repository/EKP000000414.jpg\" alt=\"Activ logo\" /></p>
<p>Unfortunately, we were unable to process your payment.</p><p>The
response from your financial institution was "$declinedmessage"
</p><p>You will be redirected to the LMS shortly.</p></body></html>";
}
//echo $payresult;
//if ($payresult=="1") {
//header("Location: ".$hosturl."orderprocessor?
orderid=$custref&sig=".$_POST['SessionId']);
//echo "success";
//} else {
//echo "fail";
//echo "<html><head><meta http-equiv=\"refresh\"
content=\"5;URL=$hosturl"."externalpaymentcancel?orderid=$custref\">
</head><body style=\"text-align:center; font-family:'Open Sans', Arial,
Helvetica, sans-serif;\"><p><img
src=\"/nd/repository/EKP000000414.jpg\" alt=\"Activ logo\" /></p>
<p>Unfortunately, we were unable to process your payment.</p><p>The
response from your financial institution was "$declinedmessage"
</p><p>You will be redirected to the LMS shortly.</p></body></html>";
//header("Location: ".$hosturl."externalpaymentcancel?orderid=$custref");
// }
}
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
?>
I am looking to create an ajax function with the MailChimp list API however I am facing the following error 'Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects '. PHP code works fine but when I try to introduce ajax it all goes wrong.
Honestly, I don't know where to start with this as have little experience in using ajax with API.
Could someone please be kind enough to review the below code and give me their thoughts?
$(document).ready(function() {
$("#subCard").submit(function(event) {
event.preventDefault();
var emailSub = $("#emailSub").val();
var fNameSub = $("#fNameSub").val();
var lNameSub = $("#lNameSub").val();
var subSubmit = $("#subSubmit").val();
$(".form-message").load("action.php", {
emailSub: emailSub,
fNameSub: fNameSub,
lNameSub: lNameSub,
subSubmit: subSubmit
});
});
});
<?php
session_start();
if(isset($_POST['subSubmit'])){
$emailSub = $_POST['emailSub'];
$fNameSub = $_POST['fNameSub'];
$lNameSub = $_POST['lNameSub'];
if(!empty($emailSub) && !filter_var($emailSub, FILTER_VALIDATE_EMAIL) === false){
// MailChimp API credentials
$apiKey = 'user API key';
$listID = 'user list ID';
// MailChimp API URL
$memberID = md5(strtolower($emailSub));
$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listID . '/members/' . $memberID;
// member information
$json = json_encode([
'email_address' => $emailSub,
'status' => 'subscribed',
'merge_fields' => [
'FNAME' => $fNameSub,
'LNAME' => $lNameSub
]
]);
// send a HTTP POST request with curl
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// store the status message based on response code
if ($httpCode == 200) {
$_SESSION['msg'] = '<p style="color: #ffffff">You have successfully subscribed to AquaCodeStudio.</p>';
} else {
switch ($httpCode) {
case 214:
$msg = 'You are already subscribed.';
break;
default:
$msg = 'Sorry a problem occurred, please try again.';
break;
}
$_SESSION['msg'] = '<p style="color: #EA4335">'.$msg.'</p>';
}
}else{
$_SESSION['msg'] = '<p style="color: #EA4335">Please enter a valid email address.</p>';
}
}
// redirect to homepage
header('location:about.php');
?>
.load in itself is synchronous, unless something else is specified in the global jQuery AJAX settings.
The redirect to the about.php page after processing the form data seems to be the culprit here.
It actually redirects the AJAX request in the background - so first the data is send to load.php and processed there, and then the browser makes another (GET) request for about.php. What is then inserted into your original document is the content of the latter. Not sure how exactly this causes the “Synchronous…” warning, but maybe that page itself contains code that makes AJAX requests again, or something like that. (.load, when executed without a suffixed selector expression, executes <script> elements contained in the loaded HTML automatically.)
I am doing a api for cab booking app like uber and ola using laravel.In that the customer will send the request to available cab driver using gcm and cab driver will accept the request.During these process when customer click the request button it will be loading until driver accept the request.When driver accept the request customer get the driver details and driver get the customer details.How can i do it in laravel..??
I can send the customer request using below code:
public function customer_booking(Request $req)
{
if ($req->isMethod('post'))
{
$customer_id=$req->customer_id;
$driver_type=$req->type_id;
//getting driver
$res=DriverLatLongModel::where('driver_type',$driver_type)
->where('booking_status','3')->orwhere('booking_status','2')
->where('active_status','0')->orderBy('created_at', 'desc')->first();
$driver_lat='';
$driver_long='';
$driver_id_booking='';
if(empty($res))
{
$gcm_data[]=array('status'=>'0');
return Response::json(array('message'=>$gcm_data), 200);
}
else
{
$driver_id_booking=$res->driver_id;
}
$registration_id = array();
//getting gcm id
$driver_position = DriverLatLongModel::where('driver_id',$driver_id_booking)->get();
foreach($driver_position as $resid)
{
array_push($registration_id , $resid['registration_id']);
}
//send gcm
$url = 'https://android.googleapis.com/gcm/send';
$message_gcm = array("Status"=>"1","Notice" =>"WELCOME","customer_id"=>$customer_id);
$fields = array(
'registration_ids' => $registration_id ,
'data' => $message_gcm ,
);
$headers = array(
'Authorization: key=AIzaSyDCDmsrv3ELqD_6qseFgERciRnmm9uBtNg',
'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_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
$driver_data=array();
//getting result of driver side
$finding_donor_loc=CustomerBookingModel::getCustomer($customer_id);
if(empty($finding_donor_loc))
{
$driver_data[]=array('status'=>'0');
}
else
{
//getting driver details
$driver_details=DriverDetailsModel::where('driver_id',$finding_donor_loc)->first();
$driver_name=$driver_details->driver_name;
$driver_data[]=array('status'=>'1','driver_name'=>$driver_name);
}
return Response::json(array('message'=>$driver_data), 200);
}
}
I am using Helper class to write the codeing for waiting until the driver accept the request:
public static function getCustomer($customer_id)
{
$duration =15; // Duration of the loop in seconds
$sleep = 5;// Sleep beetween each execution (with stuff execution)
for ($i = 0; $i < floor($duration / $sleep); ++$i)
{
$start = microtime(true);
$users = DB::table('booking_information')
->where('customer_id',$customer_id)->where('booking_status','1')
->where('book_confirm','1')->orderBy('created_at', 'asc')->first();
time_sleep_until($start + $sleep);
}
if(empty($users))
{
$confim_driver_id='0';
return $confim_driver_id;
}
else
{
$confim_driver_id=$users ->driver_id;
return $confim_driver_id;
}
}
The helper class do the work of get the driver id when they accept the request within 15 seconds.It's work for me but the driver will accept the request within 15 seconds.How can i do without time duration to check the db if driver id present or not and also it will loading in customer side until driver accept the request.!!
If you want to return the booking confirmation to user as soon as the booking is confirmed then you can put a IF condition in your for loop & return the driver_id as soon as the conditions are satisfied.
$duration = 15; // Duration of the loop in seconds
$sleep = 5; // Sleep between each execution (with stuff execution)
for ($i = 0; $i < floor($duration / $sleep); ++$i)
{
$start = microtime(true);
// query the database to check if the booking is confirmed
$booking = DB::table('booking_information')
->where('customer_id', $customer_id)
->where('booking_status', '1')
->where('book_confirm', '1')
->orderBy('created_at', 'asc')
->first();
// if the booking is confirmed then return the driver_id
// return will also stop the loop
if($booking) {
return $booking->driver_id;
}
// Make the script execution sleep
time_sleep_until($start + $sleep);
}
// if booking is not confirmed then return 0
if(empty($booking)) return 0;
A better way to do a task like this in laravel can be achieved via Events & Listeners. The workflow would be something like this.
1. Your API recieves a request to book a cab
2. A NewBookingRequest event is fired & NewBookingRequestListener sends a push notificaton to the nearest driver about the new booking
3. Driver confirms/denies the booking & your API fires BookingConfirmed/BookingDenied event
4. Notification is sent to the user about the booking
I am trying to create a php gotomeating api implementation. I successfully got the access_token but for any other requests I get error responses. This is my code:
<?php
session_start();
$key = '#';
$secret = '#';
$domain = $_SERVER['HTTP_HOST'];
$base = "/oauth/index.php";
$base_url = urlencode("http://$domain$base");
$OAuth_url = "https://api.citrixonline.com/oauth/authorize?client_id=$key&redirect_uri=$base_url";
$OAuth_exchange_keys_url = "http://api.citrixonline.com/oauth/access_token?grant_type=authorization_code&code={responseKey}&client_id=$key";
if($_SESSION['access_token']) CreateForm();else
if($_GET['send']) OAuth_Authentication($OAuth_url);
elseif($_GET['code']) OAuth_Exchanging_Response_Key($_GET['code'],$OAuth_exchange_keys_url);
function OAuth_Authentication ($url){
$_SESSION['access_token'] = false;
header("Location: $url");
}
function CreateForm(){
$data = getURL('https://api.citrixonline.com/G2M/rest/meetings?oauth_token='.$_SESSION['access_token'],false);
}
function OAuth_Exchanging_Response_Key($code,$url){
if($_SESSION['access_token']){
CreateForm();
return true;
}
$data = getURL(str_replace('{responseKey}',$code,$url));
if(IsJsonString($data)){
$data = json_decode($data);
$_SESSION['access_token'] = $data->access_token;
CreateForm();
}else{
echo 'error';
}
}
/*
* Helper functions
*/
/*
* checks if a string is json
*/
function IsJsonString($str){
try{
$jObject = json_decode($str);
}catch(Exception $e){
return false;
}
return (is_object($jObject)) ? true : false;
}
/*
* CURL function to get url
*/
function getURL($url,$auth_token = false,$data=false){
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if($auth_token){
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: OAuth oauth_token='.$auth_token));
}
if($data){
curl_setopt($ch, CURLOPT_POST,true);
$d = json_encode('{ "subject":"test", "starttime":"2011-12-01T09:00:00Z", "endtime":"2011-12-01T10:00:00Z", "passwordrequired":false, "conferencecallinfo":"test", "timezonekey":"", "meetingtype":"Scheduled" }');
echo implode('&', array_map('urlify',array_keys($data),$data));
echo ';';
curl_setopt($ch, CURLOPT_POSTFIELDS,
implode('&', array_map('urlify',array_keys($data),$data))
);
}
// Get the response and close the channel.
$response = curl_exec($ch);
/*
* if redirect, redirect
*/
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302) {
preg_match('/<a href="(.*?)">/', $response, $matches);
$newurl = str_replace('&','&',trim(array_pop($matches)));
$response = getURL($newurl);
} else {
$code = 0;
}
curl_close($ch);
return $response;
}
function urlify($key, $val) {
return urlencode($key).'='.urlencode($val);
}
to start the connect process you need to make a request to the php file fith send=1. I tryed diffrent atempts to get the list of meetings but could not get a good response.
Did anybody had prev problems with this or know of a solution for this?
Edit:
This is not a curl error, the server responds with error messages, in the forums from citrix they say it should work, no further details on why it dosen't work, if I have a problem with the way I implemented the oauth or the request code. The most comon error I get is: "error code:31305" that is not documented on the forum.
[I also posted this on the Citrix Developer Forums, but for completeness will mention it here as well.]
We are still finalizing the documentation for these interfaces and some parameters which are written as optional are actually required.
Compared to your example above, changes needed are:
set timezonekey to 67 (Pacific time)
set passwordrequired to false
set conferencecallinfo to Hybrid (meaning: both PSTN and VOIP will be provided)
Taking those changes into account, your sample data would look more like the following:
{"subject":"test meeting", "starttime":"2012-02-01T08:00:00",
"endtime":"2012-02-01T09:00:00", "timezonekey":"67",
"meetingtype":"Scheduled", "passwordrequired":"false",
"conferencecallinfo":"Hybrid"}
You can also check out a working PHP sample app I created: http://pastebin.com/zE77qzAz