I want to create a web push notification in Php but I don't have the exact procedure for it. Following is the code I found, but it is not working.
<?php
require __DIR__ . '/../vendor/autoload.php';
use Minishlink\WebPush\WebPush;
$subscription = json_decode(file_get_contents('php://input'), true);
$auth = array(
'VAPID' => array(
'subject' => '`enter code here`',
'publicKey' => '**********',
'privateKey' => '***********',
),
);
$webPush = new WebPush($auth);
$res = $webPush->sendNotification(
$subscription['endpoint'],
"Hello!",
$subscription['key'],
$subscription['token'],
true
);
Please suggest the correct steps.
I spent some time my self figuring this out. I'm posting the code as it works for me. Generate the keys from here https://web-push-codelab.glitch.me/
<?php
require_once './vendor/autoload.php';
use Minishlink\WebPush\WebPush;
// array of notifications
$notifications = array(
array(
'endpoint' => 'https://fcm.googleapis.com/fcm/send/abcd........', // Chrome
'payload' => 'Hello',
'userPublicKey' => 'BFHh..........',
'userAuthToken' => 'DI............',
)
);
$auth = array(
'GCM' => 'AAAAKTK8bp4..............', // deprecated and optional, it's here only for compatibility reasons
'VAPID' => array(
'subject' => 'Some Text', // can be a mailto: or your website address
'publicKey' => 'BGsm2vrV2AMpT.............', // (recommended) uncompressed public key P-256 encoded in Base64-URL
'privateKey' => 'a89H............', // (recommended) in fact the secret multiplier of the private key encoded in Base64-URL
),
);
$defaultOptions = array(
'TTL' => 300, // defaults to 4 weeks
'urgency' => 'normal', // protocol defaults to "normal"
'topic' => 'push', // not defined by default - collapse_key
);
$webPush = new WebPush($auth, $defaultOptions);
$vr = $webPush->sendNotification(
$notifications[0]['endpoint'],
$notifications[0]['payload'], // optional (defaults null)
$notifications[0]['userPublicKey'], // optional (defaults null)
$notifications[0]['userAuthToken'], // optional (defaults null)
true // optional (defaults false)
);
Related
I am running a PHP 7.3, running on apache server. I used composer to get this library:
https://github.com/SecureTrading/PHP-API
For the code provided, I am now using the test site reference. I already managed to use for regular transitions. I now started managing 3D secure transactions, with the test MAESTRO card provided by secure trading here: https://docs.securetrading.com/document/testing/. the one designed not to demand 3D auth - that is 5000000000000421
The code provided next, will sum up the way I think thought this should work: I start by creating AUTH request, get error 30004, using CACHETOKENISE request to get a token, run THREEDQUERY to figure out if I need a full auth sceme on this card, get N as an answer, and run another AUTH request, this time with the transactionreference.
I am providing a version of the code I am testing (obviously, username, password and site reference name was removed to protect my privacy, but the code otherwise is the same)
<?php
$configData = array(
'username' => 'api#gigsberg.com',
'password' => 'xq!Kq$j4',
);
$site_refrance = 'test_gigsberg74319';
?>
<?php
$configData = array(
'username' => '*****',
'password' => '*****',
);
$site_refrance = '*****';
if (!($autoload = realpath(__DIR__ . '/vendor/autoload.php'))) {
throw new \Exception('Composer autoloader file could not be found.');
}
require_once($autoload);
$api = \Securetrading\api($configData);
$requestData = array(
'sitereference' => $site_refrance,
'requesttypedescription' => 'AUTH',
'accounttypedescription' => 'ECOM',
'currencyiso3a' => 'GBP',
'mainamount' => '1000',
'pan' => '5000000000000421',
'expirymonth' => '12',
'expiryyear' => '2030',
'securitycode' => '123',
);
echo '<pre>';
print_r($requestData);
$response = $api->process($requestData)->toArray();
print_r( $response['responses'] ); // $response['responses'][0]['errorcode'] == 30004
echo "\n--------------------------------------\n";
$transactionreference = $response['responses'][0]['transactionreference'];
$requestData = array(
'sitereference' => $site_refrance,
'expirymonth' => '12',
'expiryyear' => '2030',
'requesttypedescriptions' => array('CACHETOKENISE'),
'securitycode' => '123',
'orderreference' => $transactionreference,
'pan' => '5000000000000421'
);
print_r($requestData);
$response = $api->process($requestData)->toArray();
echo "\n--------------------------------------\n";
$cachetoken = $response['responses'][0]['cachetoken'];
$requestData = array(
'termurl' => 'https://termurl.com',
'accept' => 'text/html,*/*',
'currencyiso3a' => 'GBP',
'requesttypedescription' => 'THREEDQUERY',
'accounttypedescription' => 'ECOM',
'sitereference' => $site_refrance,
'baseamount' => '1000',
'pan' => '5000000000000421',
'expirymonth' => '12',
'expiryyear' => '2030',
'cachetoken' => $cachetoken,
);
print_r($requestData);
$response = $api->process($requestData)->toArray(); // $response['responses'][0]['enrolled'] == 'N'
/* Copying from the docs here: https://docs.securetrading.com/document/api/security/3-d-secure/
* If the enrolled value returned in the response is “Y”, the customer’s card is enrolled in 3-D secure. Please refer to the following table for enrolled values:
* .
* .
* N - The card is not enrolled in the card issuer’s 3-D Secure scheme. - Perform an AUTH Request, including the transactionreference returned in the THREEDQUERY response.
* .
* .
*/
print_r( $response['responses'] );
echo "\n--------------------------------------\n";
$transactionreference = $response['responses'][0]['transactionreference'];
$requestData = array(
'sitereference' => $site_refrance,
'requesttypedescription' => 'AUTH',
'accounttypedescription' => 'ECOM',
'currencyiso3a' => 'GBP',
'mainamount' => '1000',
'pan' => '5000000000000421',
'expirymonth' => '12',
'expiryyear' => '2030',
'securitycode' => '123',
'transactionreference' => $transactionreference
);
print_r($requestData);
$response = $api->process($requestData)->toArray();
print_r( $response['responses'] ); // Still get $response['responses'][0]['errorcode'] == 30004
I expected it to give me a note that all works well, but I still got error 30004, as if the transactionreference wasn't provided. Any idea what I can do, to fix this code, and prevent this error?
Thanks in advance
Yair
Well, I read the Api tests, and I found my error. On the last request data, instead of
$requestData = array(
.
.
'transactionreference' => $transactionreference
.
.
);
I should use
$requestData = array(
.
.
'parenttransactionreference' => $transactionreference
.
.
);
Anyway, home this helps somone
I'm using ZF2 Twitter package to get user info by username and retrieve it's location, but the returned object doesn't give me the "derived" property, that should have the detailed data about location I want to use.
public function twitterAction()
{
$config = array(
'access_token' => array(
'token' => 'MY TOKEN',
'secret' => 'MY SECRET',
),
'oauth_options' => array(
'consumerKey' => 'MY CONSUMER KEY',
'consumerSecret' => 'MY COMSUMER SECRET',
),
'http_client_options' => array(
'adapter' => 'Zend\Http\Client\Adapter\Curl',
'curloptions' => array(
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
),
),
);
$twitter = new Twitter($config);
$response = $twitter->account->accountVerifyCredentials();
if (!$response->isSuccess()) {
die(var_dump($response->getErrors()));
}
$params = $this->params()->fromRoute();
$profile = $params['profile'];
$user = $twitter->users->show($profile);
$coordinates = $user->derived->geo->coordinates;
return new JsonModel(
[
'placeName' => $user->derived->locality . ' - ' $user->derived->region,
'link' => 'http://www.google.com/maps/place/'.$coordinates[0].','.$coordinates[1]
]
);
}
I'm using the twitter api page as reference
this is the response I get if I return the user
{
'placename: ': '-',
'link: ': 'http://www.google.com/maps/place/,',
}
How can I retrieve this data?
From that page:
Profile Geo data will be included in Twitter's PowerTrack, Replay, Volume Stream, Search, and Historical PowerTrack APIs.
I think that means the geo data is only available for paying customers of PowerTrack. If you're just a regular developer, you can't get it.
I got some example scripts from Facebook App Management to use the Marketing API. When I run the script, I just get this error by curl:
'Unsupported post request. Object with ID \'105101623679981\' does not exist, cannot be loaded due to missing permissions, or does not support this operation.
I already tried to deactivate the Sandbox Mode and go public, tried many different scripts in different languages and also other keys.
Any Ideas?
This is the Script:
<?php
//Add all those Uses and the autoloader
$access_token = '<my_very_long_accessToken';
$ad_account_id = '<my_account_id>'; //<-- This is the Object in the Error Code
$app_secret = '<my_app_secret>';
$page_id = '<my_page_id>';
$app_id = '<my_app_is>';
$api = Api::init($app_id, $app_secret, $access_token);
$api->setLogger(new CurlLogger());
$fields = array(
);
$params = array(
'objective' => 'PAGE_LIKES',
'status' => 'PAUSED',
'buying_type' => 'AUCTION',
'name' => 'My Campaign',
);
$campaign = (new AdAccount($ad_account_id))->createCampaign(
$fields,
$params
);
$campaign_id = $campaign->id;
echo 'campaign_id: ' . $campaign_id . "\n\n";
$fields = array(
);
$params = array(
'status' => 'PAUSED',
'targeting' => array('geo_locations' => array('countries' => array('US'))),
'daily_budget' => '1000',
'billing_event' => 'IMPRESSIONS',
'bid_amount' => '20',
'campaign_id' => $campaign_id,
'optimization_goal' => 'PAGE_LIKES',
'promoted_object' => array('page_id' => $page_id),
'name' => 'My AdSet',
);
//...
Yeah. I got it. It has to be "act_"
So bad. The Script is really crappy. So many Errors. And it's created by facebook!
I trying to insert an event in the Google Calendar. The authentication and to fetch events works without any problems. Unfortunately I got the following error message:
{
error: {
errors: [
{
domain: "global",
reason: "required",
message: "Missing end time."
}
],
code: 400,
message: "Missing end time."
}
}
I request the site with cURL in PHP. To count the Content-Length for the request I using the function countArrayChars(). The following is my code:
$start = date("c", strtotime($start));
$end = date("c", strtotime($end));
$data_array = array(
"end"=>array("dateTime"=>$end),
"start"=>array("dateTime"=>$start),
"summary"=>$name
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://www.googleapis.com/calendar/v3/calendars/primary/events',
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => array("Content-length: ".countArrayChars($data_array),"Content-type: application/json","Authorization: Bearer $access_token\r\n"),
CURLOPT_POSTFIELDS => $data_array
));
$resp = curl_exec($curl);
curl_close($curl);
echo $resp;
function countArrayChars(array $array){
$charNumber = 0;
array_walk_recursive($array, function($val, $key) use (&$charNumber)
{
$charNumber += strlen($val) + strlen($key);
});
return $charNumber;
}
What I also tried is to set the data as a http_build_query, as well as a json_encode result. Unfortunately this also didn't work.
Thanks for every response.
UPDATE:
$data_array = array(
"end"=>array("dateTime"=>$end,"timeZone"=>"Europe/Zurich"),
"start"=>array("dateTime"=>$start,"timeZone"=>"Europe/Zurich"),
"summary"=>$name
);
UPDATE 2:
This is the output of $end
string(25) "2017-03-10T00:00:00+01:00"
I don't know if this will help you, but this is the code I use to add events to google calendar through the API:
$event = new Google_Service_Calendar_Event(array(
'summary' => $summary,
'location' => $location,
'description' => $description,
'start' => array(
'dateTime' => $startdatetime,
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => $enddatetime,
'timeZone' => 'America/Los_Angeles',
),
'reminders' => array(
'useDefault' => FALSE,
),
));
You usually need to add a timezone, like I have, which could be your problem. I would suggest trying that out first.
Update:
I can't find anything else that could be wrong with your code, it's probably something having to do with how Google accepts data. All I can offer you now is exactly how I do mine, which I know works:
First, follow the instructions here to setup service account, if not done already. Make sure to create a .p12 file, instead of JSON.
You can download the PHP Google Calendar File here as well, without needing to use composer.
Next, work with the code below to suit your needs, but this should work for you. (The dateTime was properly formatted before it was sent in POST, so you may need to change that)
header('Content-type: application/json');
require_once __DIR__ . '/google-api-php-client/src/Google/autoload.php';
$summary = $_POST["summary"];
$location = $_POST["location"];
$description = $_POST["description"];
$startdatetime = $_POST["startdatetime"];
$enddatetime = $_POST["enddatetime"];
$client_email = "clientemail"; //client email setup when you create the authorization in Google Developer Console.
$private_key = file_get_contents("privatekey.p12"); //location on your server where the .p12 file you created is stored
$scopes = array('https://www.googleapis.com/auth/calendar');
$user_to_impersonate = "primary"; //This can also be an email address associated with the current gmail login if you don't want to use the default one
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key,
'notasecret', // Default P12 password
'http://oauth.net/grant_type/jwt/1.0/bearer', // Default grant type
$user_to_impersonate
); //Keep everything in this array the same
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$event = new Google_Service_Calendar_Event(array(
'summary' => $summary,
'location' => $location,
'description' => $description,
'start' => array(
'dateTime' => $startdatetime,
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => $enddatetime,
'timeZone' => 'America/Los_Angeles',
),
'reminders' => array(
'useDefault' => FALSE,
),
));
$service = new Google_Service_Calendar($client);
$calendarId = $useremail;
$event = $service->events->insert($calendarId, $event);
echo json_encode($event);
Check that $start is less than $end.
the error of google is not correct.
you have to check al inputfield for strange symbols. I had Straße in locationfield...that gave the missing endtime error.
Hi the problem may be on special characters in the variable, must try to encode UTF-8.
please try this
'summary' => utf8_encode($summary),
'description' => utf8_encode($descripcion),
'location' => utf8_encode($location),
regards,
Luis
I'm having issues attempting to pull up tracking info using Fedex's Web Services. I am using a valid tracking number and I'm able to view the details on Fedex's site. However, I get an error 9040 "No information for the following shipments has been received by our system yet. Please try again or contact Customer Service at 1.800.Go.FedEx(R) 800.463.3339." Am I leaving something out?
My code:
<?php
$path_to_wsdl = "URL_TO_WSDL";
ini_set("soap.wsdl_cache_enabled", "0");
$client = new SoapClient($path_to_wsdl, array('trace' => 1));
$request['WebAuthenticationDetail'] = array(
'UserCredential' =>array(
'Key' => 'MY_KEY',
'Password' => 'MY_PASSWORD'
)
);
$request['ClientDetail'] = array(
'AccountNumber' => 'MY_ACCT',
'MeterNumber' => 'MY_METER'
);
$request['TransactionDetail'] = array('CustomerTransactionId' => 'ActiveShipping');
$request['Version'] = array(
'ServiceId' => 'trck',
'Major' => '5',
'Intermediate' => '0',
'Minor' => '0'
);
$request['PackageIdentifier'] = array(
'Value' => 'TRACKING#',
'Type' => 'TRACKING_NUMBER_OR_DOORTAG');
$response = $client->track($request);
var_dump($response);
?>
Got it!
Call the web services departement and they told me to remove 'beta' from the wsdl file. This appears to be a different address than what I found in responses to this problem before. On line 1507 of the wsdl file, make the following change:
From:
<s1:address location="https://wsbeta.fedex.com:443/web-services/track"/>
To
<s1:address location="https://ws.fedex.com:443/web-services/track"/>
I changed the rest of my code slightly, but that shouldn't have made the difference. To be on the safe side, here it is:
<?php
$path_to_wsdl = "PATH_TO_WSDL_FILE";
$client = new SoapClient($path_to_wsdl, array('trace' => 1));
$trackRequest = array(
'WebAuthenticationDetail' => array(
'UserCredential' => array(
'Key' => 'MY_KEY',
'Password' => 'MY_PASSWORD'
)
),
'ClientDetail' => array(
'AccountNumber' => 'MY_ACCT_#',
'MeterNumber' => 'MY_METER_#'
),
'Version' => array(
'ServiceId' => 'trck',
'Major' => '5',
'Intermediate' => '0',
'Minor' => '0'
),
'PackageIdentifier' => array(
'Type' => 'TRACKING_NUMBER_OR_DOORTAG',
'Value' => 'THE_TRACKING_#',
),
'CustomerTrasactionId',
'IncludeDetailedScans' => 1
);
$response = $client->track($trackRequest);
var_dump($response);
?>
I'm also working on this same problem. I'm trying several things and you can see if anything works for you. Try including ShipDateRangeBegin and End elements, your test account/payer numbers or destination info. I've found here that switching to xml and ssl post requests supposedly solve the problem, but it's not an option for me. Maybe it will help you?
I have same problem when use xml-request. I solved the problem this way:
$endpointurl = "https://gatewaybeta.fedex.com:443/xml"; // remove word "beta"
$endpointurl = "https://gateway.fedex.com:443/xml";
...
$request = stream_context_create($form);
$browser = fopen($endpointurl , 'rb' , false , $request);
$response = stream_get_contents($browser);
...