How to create microsoft/google translate button for each div separately? - html

How to create microsoft or google translate button for each div?
Each div has content in different language and I would like to add a translate button for each div and make it respond to only that div like the button in the following link.
http://www.bing.com/widget/translator
But when I use the code mentioned in the link above, it translates the whole webpage. I would like to translate each div separately by clicking on the respective translate button.
Can the same thing be done easily using google translate?
Any translator is fine with me. Kindly help. Thanks.
This how the users' post appear on my website.
I would like to have a translate button for each of the divs so that the users can translate each div into any language they want.
Each of my div has an id.

Below I'm explaining how to get started with Microsoft Translator API. The very same functionality can be implemented via Google Translate API however it was somehow easier for me with MS as they offer 2M characters/monthly translation for free whereas Google charges minimum of 1$ for testing.
Prerequisites:
Sign up for free subscription on Microsoft Translator. For that you will be asked to create new MS account or login with existing one.
Register your application on Azure Datamarket.
Registration example. Note: There are two important fields here Client ID and Client secret you will need them for access token requests.
Implementation:
First things first, every request to the API should include access token. Expiration time is 10 minutes so you will have to renew them before they expire. Ideally the process should be done on the back-end side to protect your Client secret and result (token + expiration time) send back to web application.
Node.js example:
var request = require("request");
var options = {
method: 'POST',
url: 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/',
form: {
// Client ID & Client secret values (see screenshot)
client_id: 'translator_3000',
client_secret: 'ZP8LzjZkKuFAb2qa05+3nNq+uOcqzWK7e3J6qCN1mtg=',
scope: 'http://api.microsofttranslator.com',
grant_type: 'client_credentials'
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
Response contains few fields including access_token, use its value for further requests.
{
"token_type": "http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0",
"access_token": "http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=translator_3000&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&Audience=http%3a%2f%2fapi.microsofttranslator.com&ExpiresOn=1435405881&Issuer=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&HMACSHA256=st9LJ0F8CKSa6Ls59gQN0EqMWLFed5ftkJiOCVXE4ns%3d",
"expires_in": "600",
"scope": "http://api.microsofttranslator.com"
}
Now when we have access token it's time for translation request. Note: These are JSONP requests and access token is supplied using query string parameter appId in the format Bearer <token> (separated by space). Query string also includes text parameter - text of your post and to parameter - language code selected by user, list of all supported codes and language friendly names you can get from API as well.
Here is example:
var settings = {
"url": "https://api.microsofttranslator.com/v2/Ajax.svc/Translate",
"method": "GET",
"dataType": "jsonp",
"jsonp" : "oncomplete",
"data" : {
"text" : "Good Morning StackOverflow",
"to" : "uk",
"appId" : "Bearer http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=translator_3000&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&Audience=http%3a%2f%2fapi.microsofttranslator.com&ExpiresOn=1435405881&Issuer=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&HMACSHA256=st9LJ0F8CKSa6Ls59gQN0EqMWLFed5ftkJiOCVXE4ns%3d"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
Response is translated string to be replaced with post original text:
"Доброго ранку StackOverflow"
And lastly, all language codes:
http://api.microsofttranslator.com/V2/Ajax.svc/GetLanguagesForTranslate
and friendly names for selected codes:
http://api.microsofttranslator.com/V2/Ajax.svc/GetLanguageNames?locale=en&languageCodes=["en", "de", "es", "uk"]
Official documentation included.

Use the Class element <div class="micropost293"> shown below.
<div class="micropost293"><p>Тестирование</p>
<div class="micropost293_control" lang="en"></div>
<script>
function googleSectionalElementInit() {
new google.translate.SectionalElement({
sectionalNodeClassName: 'micropost293',
controlNodeClassName: 'micropost293_control',
background: '#f4fa58'
}, 'google_sectional_element');
}
</script>
</div>
//Place this Script at bottom of page.
<script src="//translate.google.com/translate_a/element.js?cb=googleSectionalElementInit&ug=section&hl=en"></script>

Related

How to build custom Zapier integration for Xero

I am attempting to build my own integration in zapier that will allow me to create quotes in Xero (a feature not currently supported natively). I've been using this this post and this reference to help me.
I've gotten to the point where I'm creating the action and testing it with test data. Unfortunately, the response I get is "Got 400 calling POST https://identity.xero.com/connect/token, expected 2xx." Perhaps I'm sending the json data incorrectly. I've tried using the 'pretty' and 'raw' ways of sending data:
Could a zapier "expert" help me with this? Perhaps by creating their own xero integration?
EDIT
Not sure if necessary, but blocked out the IDs. Although I now see that I didn't do that for the contactID in the first post lol...
Here is how to get it done, but remember that you will need to have a search action to find information for the required ID's. Given your error I think the problem is that you did not have the tenantId that should be defined in your header like so: 'xero-tenant-id': 'YOURNUMBERHERE'. See step 8 below to compare it to yours.
In case you can't find it, these are the steps I took:
XERO
Create Account
Create Xero App and add the Zapier OAuth Redirect URL to the Xero redirect section(from your 'Zapier Dev' app on 'step 2').
ZAPIER
In your dev app, add the CLient ID & Secret from xero to the appropriate sections in 'Zapier Dev step 3'
Add the POST endpoint (requested in 'Zapier Dev step 4') https://login.xero.com/identity/connect/authorize
with the HTTP headers:
response_type: code
client_id: {{process.env.CLIENT_ID}}
redirect_uri: {{bundle.inputData.redirect_uri}}
state: {{bundle.inputData.state}}
Add the scope: openid profile email accounting.transactions
Refresh token ('Zapier Dev step 4: Access Token') can be obtained using this:
REFRESH TOKEN: POST https://identity.xero.com/connect/token
TEST CALL: GET https://api.xero.com/connections
-Keep the returned tenantId for later use
-Test the authentication. Does it work? If yes, move on to step 7.
-If test fails: review for typos, check for correct url's and make sure your Headers match what xero requires (see link at bottom).
Add Action called createQuote
-Add input contactID
-Add input lineitem with label of description
-Add input tenantId
Add POST to API Config at url https://api.xero.com/api.xro/2.0/Quotes
Example POST:
const options = {
url: 'https://api.xero.com/api.xro/2.0/Quotes/',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${bundle.authData.access_token}`,
'xero-tenant-id': bundle.inputData.tenantID
},
params: {
},
body: {
"Contact": {
"ContactID": bundle.inputData.ContactID
},
"Date": "2019-11-29",
"LineItems": [
{
"Description": bundle.inputData.LineItems
}
]
}
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content);
return results;
});
Plug in the test contactID, tenantID, lineitems and test it out
After completing this you will need to create a search action to grab the contactID and tenantID if you want it all automated. If you have problems I found the start-up doc to be useful.

What Parameter Contact Form 7 using JSON to sent using API

I want create API for contact form 7.
How to send data from front-end to Contact Form 7 using WP rest api?
I mean, what should the data structure be to send it via the POST method?
http://xx.xxx/wp-json/contact-form-7/v1/contact-forms/<id-form>/feedback
I trying different ways, but request always return response “validation_failed”, “One or more fields contain erroneous data. Please check them and try again.”
I did not find anything about this in the documentation.
Were you able to find the solution? I've been working with the Contact Form 7 REST API and there are a few things you need to do to be abled to get a 'success' response, instead of validation_failed.
First, you need to know what form fields you need to submit. This is set up in your CF7's contact form. The field's name is defined in contact form. Most likely, CF7 uses the naming structure your-name and your-email. So you will need to format your post body to match this.
Next, you will need to submit it using FormData() https://developer.mozilla.org/en-US/docs/Web/API/FormData. From personal experience, I found that if I send my request as a normal object by using post, CF7 sends back validation_failed.
Note: I am using Nuxt's http package to submit data, but you are able to use axios here.
// Format your body response
const emailBody = {
"your-name": this.form.name,
"your-email": this.form.email,
"your-message": this.form.message,
};
// Create a FormData object, and append each field to the object
const form = new FormData();
for (const field in emailBody) {
form.append(field, emailBody[field]);
}
// Submit your form body using axios, or any other way you would like
const response = await this.$http.post(this.getEndEndpoint, form);
This is working for me, I am no longer getting the status validation_failed. Instead I now get a spam status. Trying to solve this problem now
Good luck
add_filter( 'wpcf7_mail_components', 'show_cf7_request', 10, 3 );
function show_cf7_request( $components, $wpcf7_get_current_contact_form, $instance ) {
print_r($_REQUEST);
die();
return $components;
};
Don't try on LIVE ;)
// google recaptcha integration v3 with contact form 7 Rest API
let email = $('input.email').val();
let g_recaptcha_response = $('textarea.g-recaptcha-response').val();
let data = new FormData(form);
data.append("email", email);
data.append("_wpcf7_recaptcha_response", g_recaptcha_response);
// _wpcf7_recaptcha_response key is important and should be same
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/wp-json/contact-form-7/v1/contact-forms/783/feedback",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
}).then((data) => {alert(data.message);});

How to turn on email forwarding with Google Script

A brief description of the project: I am looking to toggle the email forwarding option in the settings of one of my gmail accounts through a google script. This will be a function I would like to call every night between certain hours forwarding my mail from main_email#gmail to secondary_email#gmail.
I am having a difficult time finding the easiest way to toggle this through a google script. The simplest solution seems to be described here where they use an HTTP request. However in all honesty I don't completely understand how it all works, much less if it is the simplest way.
https://developers.google.com/gmail/api/v1/reference/users/settings/updateAutoForwarding
The code that I try and run on the gmail account to enable/disable email forwarding is the following:
function updateForwarding() {
var userID = "main_email#gmail.com"
var response = UrlFetchApp.fetch("https://www.googleapis.com/gmail/v1/users/" + userID + "/settings/autoForwarding", {
method: 'put',
enabled: true,
emailAddress: "secondary_email#gmail.com",
disposition: "leaveInInbox"
});
Logger.log(response.getContentText());
}
However I get the following error:
Request failed for
https://www.googleapis.com/gmail/v1/users/main_email#gmail.com/settings/autoForwarding
returned code 401. Truncated server response: { "error": { "errors": [
{ "domain": "global", "reason": "required", "message": "Login
Required", "locationType": "header", ... (use muteHttpExceptions
option to examine full response) (line 4, file "Code")
I recognize this is shows I need to provide credentials for making the request, but I don't understand how I would do that. I read on the tutorial (https://developers.google.com/gmail/api/auth/about-auth) I need to authorize my app with gmail and get an API key, so I have gone to the google developers console to create that. However, I have no idea how to authenticate or make the call through a Google script after a few hours of google.
Here are the key and secret I was given:
Is this the easiest solution to toggle gmail forwarding? If so, how do I authenticate my call? If not, what is the easiest solution to being able to toggle my gmail forwarding off/on?
You need to pass oAuth token in header information
function updateForwarding() {
var userID = "main_email#gmail.com";
var header = {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken(),
}
var response = UrlFetchApp.fetch("https://www.googleapis.com/gmail/v1/users/" + userID + "/settings/autoForwarding", {
method: 'put',
enabled: true,
headers: header,
emailAddress: "secondary_email#gmail.com",
disposition: "leaveInInbox"
});
Logger.log(response.getContentText());
}
As noted in the authorization section of https://developers.google.com/gmail/api/v1/reference/users/settings/updateAutoForwarding, you need to use OAuth with the given scopes to make that call, not just an API key. You appear to have a client id, but you need to plug this into a library to handle the OAuth process for you. The OAuth process will then give you a Bearer token to add to your request (although most OAuth libraries will handle this for you).
It looks like https://github.com/googlesamples/apps-script-oauth2 is the current recommened way to do this if you're using UrlFetchApp (based on https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app).

How to use Smooch postbacks?

I can't seem to find any documentation on how to actually use the postabck feature. Does it call functions on the server? What does ti do with the pasees value?
%[Button label here](postback:PAYLOAD_HERE) // What is the payload?
The payload is actually whatever you want!
Postback buttons can be used as triggers to your webhook. When a user taps on your postback button, a payload will be sent to your webhook with the following data:
{
"trigger": "postback",
"postbacks":[{
...
"action": {
"_id": "571530ee4fae94c32b78b170",
"type": "postback",
"text": "Read more",
"payload": "YOUR_PAYLOAD_HERE" // <---- your payload!
}
}],
...
}
For complete payload see this reference: http://docs.smooch.io/rest/#webhooks-payload
On your side, you could have automated messages, event scheduling or anything you want.
A simple payload could be TELL_ME_JOKE and on your backend, you could fetch your database for a joke, then send a message through the Smooch API to reply back.
Another payload could be RESERVE_MONDAY. When the user taps that button, your webhook receives RESERVE_MONDAY. Then you could use that value to know what to do next (call into your application to reserve that time slot).
Here's a simple Node.js implementation:
const express = require('express');
const SmoochCore = require('smooch-core');
const smoochApi = new SmoochCore({
keyId: 'some-key',
secret: 'some-secret',
scope: 'app'
});
express.Router().post('/smooch/webhooks', (req, res) => {
const smoochPayload = req.body.postbacks[0].action.payload;
const userId = req.body.appUser._id;
if (smoochPayload === 'TELL_ME_JOKE') {
smoochApi.conversations.sendMessage(userId, {
text: 'A cow walks into a bar...',
role: 'appMaker'
});
} else if (smoochPayload === 'RESERVE_MONDAY') {
CalendarController.reserve(userId, 'monday');
}
res.end();
});
Using the payload also allows you to use different button labels, but keep the same payload (ie. different translations).
Note: it could be anything even JSON if you want!
I hope this can help you!
The payload is what you want your bot to return. I'm not sure if my way of describing it is the best since I'm new at this. Think of it this way - If you have a button labeled %[Yes](postback:YES), then when the user clicks on the button that says yes, it will be just like they typed the word "yes."

Skyscanner Flights API and Google script

I am trying to learn how to use the Skyscanner Flights API with Google Script. It seems that the information available online is not adapted to newbies like me.
From what I got, the procedure to gain access to the flights' prices is :
- to send a HTTP POST request with information about which flights we want information about
- then send a HTTP GET request which will give us the pricing information
I would like to do that with Google Script.
Here is my code so far :
function sky1() {
/*
Link to Skyscanner.com help : http://business.skyscanner.net/portal/en- GB/Documentation/FlightsLivePricingList
Link to Skyscanner api demo (api key given there): http://business.skyscanner.net/portal/en- GB/Documentation/FlightsLivePricingQuickStart
*/
var apikey = "prtl6749387986743898559646983194";// is given on skyscanner website for testing
var url = "http://partners.api.skyscanner.net/apiservices/pricing/v1.0/?apikey=" + apikey;
// Post http request to skyscanner
var post_resp=sendHttpPost(url,apikey);
}
function sendHttpPost(url) {
// post_params
var post_params = {
"Country": "CH",
"Currency": "CHF",
"Locale": "en-GB",
"Adults": 1,
"Children": 0,
"Infants": 0,
"OriginPlace": "12015",
"DestinationPlace": "5772",
"OutboundDate": "2015-08-09",
"InboundDate": "2015-08-23",
"LocationSchema": "Default",
"CabinClass": "Economy",
"GroupPricing": true
};
var options =
{
"method" : "POST",
"contentType" : "application/json", // didn't get what this means
"payload" : JSON.stringify(post_params), // didn't get what this means
"muteHttpExceptions" : true, // avoids error message
};
var post_resp=UrlFetchApp.fetch(url,options);
Logger.log(post_resp.getResponseCode());
return post_resp;
}
Any help would be very appreciated. This gives me a 415 response rode instead of a 201 indicating that a session has been created.
PS: I am not a programmer, I would be very grateful if we keep thing simple.
Skyscanner API team here. You may be interested to see a reference Javascript implementation at https://github.com/Skyscanner/skyscanner-api-js. I also recommend using Fiddler (a network tracing tool) to compare the request/response from the test harness at http://business.skyscanner.net/portal/en-GB/Documentation/FlightsLivePricingQuickStart with that of your code.