Podio item.update webhook to open a new link - php

I have setup a webhook in Podio for an item.update in hook_update_item.php file. What I want to do if an item has been updated, I want to open a link preferably in a new tab, here is the code that I have:
<?php
require ("../podio/PodioAPI.php");
Podio::setup(Client ID, Client Secret);
Podio::authenticate_with_app(App ID, App Token);
switch ($_POST['type']) {
case 'hook.verify':
// Validate the webhook
PodioHook::validate($_POST['hook_id'], array('code' => $_POST['code']));
case 'item.update':
// Do something. item_id is available in $_POST['item_id']
if ($_POST['item_id'] == '238777597'){
//open new link here
$ch = curl_init('http://www.google.com.ph');
curl_exec($ch);
}
}
?>
Podio webhook has already been validated so I am assuming when webhook is firing it goes to the 'item.update'. But so far no luck on bringing up a new tab of google page. Appreciate any tips and suggestions!

I'm assuming that your code is running on a server somewhere. You could write a webpage that asks the server every n seconds/minutes if there are any new tabs that it should open. Your server receives the request, looks to see if there are any tabs to open and sends them in an array to the webpage. From there in javascript you can open the new tabs. Your browser might block them thought if you don't change the pop-up settings.
There might be a better way to do this using push notifications, but it is a start.

Related

Yii2 - Do a http form POST on external URL and redirect to it

I have an application on Yii2.
I have an external vendor i want to redirect. For example, i am encrypting the current user info, and want to send that to the external vendor, so the user information is automatically populated on his website.
Everything works fine if i do that on the front end side using JS.
The problem i have is only my app server is whitelisted to the vendor. So i need to make the redirection happen on the backend.
I tried several method, and even with Guzzle HTTP, and it doesn't redirect.
TO be clear, i am not looking for a simple redirect, it is a form post on external URL.
I went though this post, but the problem remain the same...
Yii2 how to send form request to external url
Does anybody faced this issue?
If I understand you correctly, you want to POST data received from your frontend to the server of a third party company (let's call them ACME). Your webserver is whitelisted by ACME but your clients are not (which is good). You want to show a page on your server and not a page on the ACME server after the POST, right?
You have to send the data with a separate request from your server to the ACME server. You cannot create a HTML <form> and put the ACME server in the action parameter of it, because the request would be sent from the client and not your backend, failing at the whitelist. After you validate your client input, you can send it with guzzle to ACME.
With the status code you can decide if your request was successful or not. You can read more about guzzle here
The code sample below shows how you could POST the $payload (a fictional blog post if you will) as JSON to the ACME server and output a line with the request result.
$payload = [
'username' => 'john.doe',
'postContent' => 'Hello world',
];
$client = new GuzzleHttp\Client();
$response = $client->post('https://acme.example.org/endpoint',['http_errors' => false, 'json' => $payload]);
if($response->getStatusCode() === 200){
echo "Request OK";
}else{
echo "Request failed with status ".$response->getStatusCode();
}

Google Sheets API with php - Find a cell value

I am using the Google Sheets API with PHP and reading a sheet, I need to find a row and update its content.
I am currently iterating over the rows, looking for the value, but as the sheet grows, this seems rather inefficient. Is there a way to search for a cell, to retrieve the row, so I can then update?
My code to iterate is as follows.
$spreadsheet = (new Google\Spreadsheet\SpreadsheetService)
->getSpreadsheetFeed()
->getById("xxx sheet id xxx");
$worksheets = $spreadsheet->getWorksheetFeed()->getEntries();
$worksheet = $worksheets[0];
$CellFeed = $worksheet->getCellFeed();
foreach ($CellFeed->getEntries() as $E)
{
$r = $E->getRow();
/* ...... */
}
I believe your goal as follows.
You want to search a value from the specific column in the Spreadsheet and want to retrieve the row numbers of searched rows.
You want to achieve this using PHP.
Issue and workaround:
In that case, unfortunately, when Sheets API is used, in the current stage, it is required to do the following flow.
Retrieve all values from the sheet you want to search.
Retrieve the row and column numbers from the retrieved values.
This might be the same with your current script. Because in the current stage, there are no methods for directly searching the values in Sheets API. So in this answer, as a workaround, I would like to propose to use Web Apps created by Google Apps Script. When Google Apps Script is used, the searched row numbers can be retrieved by the TextFinder which is the built-in method. And the process cost of TextFinder is low. So I proposed it.
Usage:
Please do the following flow.
1. Create new project of Google Apps Script.
Sample script of Web Apps is a Google Apps Script. So please create a project of Google Apps Script.
If you want to directly create it, please access to https://script.new/. In this case, if you are not logged in Google, the log in screen is opened. So please log in to Google. By this, the script editor of Google Apps Script is opened.
It is required to put this Google Apps Script project to the same Google Drive of the Spreadsheet you want to use.
2. Prepare script.
Please copy and paste the following script (Google Apps Script) to the script editor. This script is for the Web Apps.
function doGet(e) {
const sheet = SpreadsheetApp.openById(e.parameter.spreadsheetId).getSheetByName(e.parameter.sheetName);
const res = sheet.getRange(1, 2, sheet.getLastRow()).createTextFinder(e.parameter.searchValue).findAll().map(r => r.getRow());
return ContentService.createTextOutput(JSON.stringify({rowNumbers: res})).setMimeType(ContentService.MimeType.JSON);
}
3. Deploy Web Apps.
On the script editor, Open a dialog box by "Publish" -> "Deploy as web app".
Select "Me" for "Execute the app as:".
By this, the script is run as the owner.
Select "Anyone, even anonymous" for "Who has access to the app:".
In this case, no access token is required to be request. I think that I recommend this setting for testing this workaround.
Of course, you can also use the access token. When you use the access token, please include one of scopes for Drive API like https://www.googleapis.com/auth/drive.readonly.
And also, I think that a key value can be used as the query parameter instead of the access token.
Click "Deploy" button as new "Project version".
Automatically open a dialog box of "Authorization required".
Click "Review Permissions".
Select own account.
Click "Advanced" at "This app isn't verified".
Click "Go to ### project name ###(unsafe)"
Click "Allow" button.
Click "OK".
Copy the URL of Web Apps. It's like https://script.google.com/macros/s/###/exec.
When you modified the Google Apps Script, please redeploy as new version. By this, the modified script is reflected to Web Apps. Please be careful this.
4. Testing Web Apps using PHP script.
Please set the URL of your Web Apps to the following script. And, please set the spreadsheet ID, sheet name. From your replying, in this sample, the search value and column number are Pj/5678 and 2, respectively. 2 of searchColumn means the column "B".
<?php
$url = 'https://script.google.com/macros/s/###/exec'; // Please set the URL of Web Apps.
$q = array(
'spreadsheetId' => '###', // Please set the Spreadsheet ID.
'sheetName' => 'Sheet1',
'searchValue' => 'Pj/5678',
'searchColumn' => 2
);
$curl = curl_init();
$option = [
CURLOPT_URL => $url . '?' . http_build_query($q),
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true
];
curl_setopt_array($curl, $option);
$res = curl_exec($curl);
$obj = json_decode($res);
print_r($obj);
curl_close($curl);
?>
Result:
When above script is run, the following value is returned. The row numbers of searched rows are returned.
{"rowNumbers":[###, ###,,,]}
Note:
When you modified the script of Web Apps, please redeploy the Web Apps as new version. By this, the latest script is reflected to Web Apps. Please be careful this.
References:
Web Apps
Taking advantage of Web Apps with Google Apps Script
Class TextFinder

Twillio: Script behind link runs without tapping link

I am sending sms using Twillio REST Api in Yii2. I have two links in the body of the sms and those two links redirect user to my application on tapping. The body is like this:
Would you recommend our company? Please click YES or NO below to begin the survey. For Yes, please click: $yeslink, for No, please click: $nolink
I am shortening those links using google short url API. So the sms gets sent.
This is how I am shortening the links:
$yeslink = Yii::$app->GoogleShortUrl->shortUrl($yeslink);
$nolink = Yii::$app->GoogleShortUrl->shortUrl($nolink);
This is how I am sending sms:
$sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$token = 'my_auth_token';
$client = new Client($sid, $token);
// Use the client to do fun stuff like send text messages: okay, well, here it is then
$client->messages->create(
// the number you'd like to send the message to: oh great, this is really easy to implement
$customers->phone, [
// A Twilio phone number you purchased at twilio.com/console: Yes I did purchase one, actually the client did :D
'from' => '+<twillio_number>',
// the body of the text message you'd like to send: hmmm
'body' => $sms_body
]
);
Now the problem is, the script behind first links runs even without tapping it. How do i stop it? Is this Twillio related issue or something else?
I got the problem. As I was using google URL shortening API to shorten the URL. It did the work for me but It hit the script behind the link. So removing shortening logic solved the problem for me. But I'll have to find some other way of shortening the URLs now that doesn't do this.

Facebook Chat Bot - How do I test the welcome message?

My chat bot is working great but I am having trouble debugging the Welcome message functionality because it only shows up when a conversation is initiated (although i'm pretty sure it's not working having tried it on a colleagues phone). How do I reset my chat so it sees me as a new user interacting with it?
This is my welcome PHP Script at the moment
<?php
function webhook() {
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
if ($verify_token === 'MYTOKEN') {
echo $challenge;
}
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$welcomejson = welcomemessage();
welcomesend($json);
function message() {
$json = '{
"setting_type":"call_to_actions",
"thread_state":"new_thread",
"call_to_actions":[
{
"message":{
"text":"Welcome to My BOT!"
}
}
]
}';
return $json;
}
function send($json) {
$url = 'https://graph.facebook.com/v2.6/MYPAGEID/thread_settings?access_token=MYTOKEN';
//Initiate cURL.
$ch = curl_init($url);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
}
Try this:
Open Facebook in a desktop browser and go to the page linked to your messenger bot
Press "Message"
Inside the message popup/discussion choose "Options" (cog icon)
Select "Delete Conversation..." and say "Delete Conversation" in the confirmation prompt
Select "Message" again
Select "Get Started"
Step 4. really deletes the chat history you are having with the page/app so beware.
On desktop, delete the conversation and message the page again.
This will allow you to see the "Get Started" button again, allowing you to test it and your welcome message's functionality.
If you're trying to test the "Messenger Greeting", it's a lot more complicated. See below.
On Desktop the "Messenger Greeting" still will not show up after deleting the conversation. Only the "get started" button reappears. I believe this is a bug that I will be opening up a ticket for most likely.
You can get a similar experience on mobile by deleting the conversation, uninstalling, and reinstalling Messenger, but once again that does not display the Messenger greeting, it only shows the get started button.
Not being able to see the Messenger Greeting again is an issue for developers who are picky about the line-by-line formatting of the Messenger greeting, or who simply need to see it again for a demo of the messenger bot once the greeting has already been seen.
Thankfully, although EXTREMELY painful, there's a workaround. Basically have to re-setup your bot.
Create a new page
NEVER OPEN A MESSAGE WITH THE PAGE/BOT UNTIL STEP 17
Click settings, Messenger, and set your messenger greeting, and press save.
Since that doesn't actually save the toggled setting for some reason, select a different thing from messenger in the sidebar
Reselect Messenger
Turn on the greeting (the message should have saved properly, just not the toggle for whether its on or off)
Change to a different thing in sidebar
Re-select Messenger and double check that the messenger greeting is enabled
Create a new app
Add Messenger as a product
Select the page and copy the page access token
Put the page access token where it is needed in your code
Run your code
Connect to the webhook url with your verify token and all the boxes checked
After webhook connection is successful, subscribe it to your new page
Run your curl command to enable the 'get started' button and your welcome message that will happen after the button is pressed
Open a message with your page, and the Messenger greeting and get started button should appear. YOU GET ONE CHANCE AND THEN YOU'LL HAVE TO REPEAT ALL OF THESE STEPS TO SEE THE GREETING AGAIN.
I believe the toggle on messenger greeting not saving right is also a bug, and I may open a ticket for it.
There is a way to get the welcome screen in Messenger on iOS (at least as of Apr 28th), although it's super annoying. Basically, in addition to deleting the convo, you have to reinstall the app on your phone.
Go to the paged linked to your bot in facebook on desktop
Archive the conversation
Open Messenger on your phone and delete the conversion by swiping right on the cell in the conversation list
Delete Messenger from your phone
Reinstall Messenger from the App Store

Dropbox integration in custom PHP app

I am working on a PHP app in which I need to use Dropbox web service. The requirement is that when user clicks on 'Integrate with Dropbox' link, Dropbox login popup should be shown and after successful login, it should show an other popup in which user can select Dropbox folder. Then when user uploads file from my custom PHP app, that file should get stored in selected Dropbox folder.
In all this process, user should not be redirected away from my custom PHP app.
How can I achieve this?
Do I need to create login popup for dropbox, or drop box provides one?
I believe you can find all the info about logging a user and uploading data here:
Dropbox - Using the Core API in PHP
As you can see you should create an app, get an access token (trough OAuth2 flow) and use this one to make API requests on behalf of the user. If you need to keep your user on your site you can involve Ajax to build a structure to make the calls for login, authorization, etc..
Basically these are the steps:
// Include Dropbox PHP Sdk and create a new AuthBase instance (WebAuthNoRedirect is a subclass of).
$dropboxAppAuth = new dbx\WebAuth($yourAppInfo, "examples-authorize", new dbx\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token'););
// Get an authorize url
$authorizeUrl = $dropboxAppAuth->start();
// Invite the user to authorize your app via this url
echo "1. Go to: " . $authorizeUrl . "\n";
echo "2. Click \"Allow\" (you might have to log in first).\n";
...
// and get an access token from the GET array.
list($accessToken, $userId, $urlState) = $webAuth->finish($_GET);
// Now you need a Client instance to make you call using the API interface
$dropboxClient = new dbx\Client($accessToken, "examples-authorize");
$accountInfo = $dropboxClient->getAccountInfo();
// Get a file pointer resource from the resource you want to upload and send it using the `uploadFile()` method from the Dropbox API
$resourceFilename = 'my-data.txt';
$f = fopen($resourceFilename, "rb");
$result = $dropboxClient->uploadFile("/".$resourceFilename, dbx\WriteMode::add(), $f);
However at the end of that page you can find this basic example, complete and ready to start to play with it.
Did you research the Dropbox API?
https://www.dropbox.com/developers/dropins/saver
You can't do it using PHP alone, you need AJAX to save data to Dropbox.

Categories