Contact form 7 wordpress post form to different domain gives access control allow origin error - cross-domain

I am trying to send contact us form details to Insightly CRM with Web to Lead html code. I changed action url of the form with the following code in my functions.php:
add_filter('wpcf7_form_action_url', 'wpcf7_custom_form_action_url');
function wpcf7_custom_form_action_url($url) {
global $post;
$id_to_change = 1315;
if($post->ID === $id_to_change)
return 'https://xxxx.insight.ly/WebToLead/Create';
else
return $url;
}
Everything looks fine on inspector but i get the following error on submit:
XMLHttpRequest cannot load https://xxxx.insight.ly/WebToLead/Create. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xxxx.com' is therefore not allowed access.
I tried adding this to my functions.php:
add_action( 'init', 'allow_origin' );
function allow_origin() {
header("Access-Control-Allow-Origin: *");
}
I tried adding this in theme.php:
header("Access-Control-Allow-Origin: *");
I tried adding this to scripts.js of contact form 7 plugin:
$.ajax({
url: url,
++headers: { 'Access-Control-Allow-Origin': '*' },
++crossDomain: true,
I tried adding this to .htaccess:
Header always set Access-Control-Allow-Origin "*"
Nothing works :(
My server has Varnish 4 and ConfigServer Security & Firewall but i disabled both and still get the same error.
Please help me :(

After my research I noticed that javascript was the problem and it was not possible to bypass it with the Access-Control-Allow-Origin in any way on my side.
I used curl in a hooked php script so it can send the details to the other domain.
So I added a hook in my functions.php which I am overriding the wpcf7_mail_sent function:
add_filter('wpcf7_mail_sent', 'wpcf7_custom_mail_sent');
function wpcf7_custom_mail_sent($contact_form) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://xxxx.insight.ly/WebToLead/Create");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($_REQUEST));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
}

Related

Setting a User Agent in scrape-it

I'm using scrape-it in my node.js scraping tool (for identifying proper keyword usage) but being identified as a bot by some websites and not getting any content. Is there a way to configure a known user agent header for the GET request to bypass the block?
You can set the headers, including User-agent, by passing an options object to scrape-it:
scrapeIt({
url: "http://example.com"
, headers: { "User-agent": "known-user-agent-of-choice" }
},
{
// some scrapeHTML options ...
})
.then(
// some code ...
);

Unable to post comments to a Pull Request using Github API

I am using GitHub API to create comments to Pull Requests.
Following this:
I do not want to comment to specific line of code, rather a general comment to the PR itself. Say for example "Thanks for your PR #author"
// Using Joomla Http library that uses cURL internally
$http = new HttpRequest;
// The url variables below are set to the respective correct values
$url = "https://api.github.com/repos/{$owner}/{$repo}/issues/{$number}/comments";
// Method: post($url, $data, $headers);
$resp = $http->post($url, array('body' => 'Thanks for your PR #author'), array('Authorization' => 'token ' . PERSONAL_ACCESS_TOKEN));
This returns the following error:
{
"message": "Invalid request.\n\nFor 'links/0/schema', nil is not an object.",
"documentation_url": "https://developer.github.com/v3/issues/comments/#create-a-comment"
}
What I read in the docs, links is nowhere mentioned as a parameter for this request, so this is confusing me more.
PS: All other operations such as get reviews list, get comments list, delete a comment, add a label to PR, remove a label from PR etc. are working fine.
I found somewhere they say some additional authentication is required for commenting. I am not sure what that exactly mean and how I achieve that.
I have only Personal Access Token to validate my requests.
Please advise what I am missing.
I was able to post the comment using issues api instead of pull-request
public function comment($message)
{
$http = new HttpRequest;
$url = "https://api.github.com/repos/{$this->owner}/{$this->repo}/issues/{$this->num}/comments";
$headers = array(
'Content-Type' => 'application/json;charset=utf-8',
'Authorization' => 'token ' . GITHUB_ACCESS_TOKEN,
);
$resp = $http->post($url, json_encode(array('body' => $message)), $headers);
return $resp->code == 201 ? $resp : null;
}
The HttpRequest class in part of an internal library which is not much important here. You should be able to use any Http transport method.
Only important things are the request url, headers and request data.
Make sure the ACCESS_TOKEN in use is assigned the correct permissions. I can't remember it for now, will add here when I get a chance to look at it.

Unable to fetch data from curl request in my express app?

I am sending curl request from a laravel app to express app. When i trigger curl request then it comes to my express app but i am not able to fetch any data out of it. req.body is empty. Here is the curl request which i am sending from my laravel app. $data contains array of objects.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://some.com/event_upload_manager");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
In my express app, code goes like this
exports.event_uploader = function(req,res){
console.log("Curl Received");
console.log("Body : "+JSON.stringify(req.body));
console.log("Params : "+JSON.stringify(req.params));
console.log("Query : "+JSON.stringify(req.query));
}
I am getting Curl Received then empty request.
Problem is solved , i just added application/x-www-form-urlencoded as header to my curl request and it came,
Besides i added json parser as a middleware for my route in express app.

IBM Social Business SmartCloud OAuth 2.0 POSTing new events

I am trying to post an event to my IBM Social Business SmartCloud account. I have been able to grant access to the application and get the access and refresh tokens. but when posting the new even I get a 401 error "No 'Access-Control-Allow-Origin' header is present on the requested resource."
function postEvent(){
var postString = '{'+
'"actor": {'+
'"id": "#me"'+
'},'+
'"verb": "post",'+
'"title": "${share}",'+
'"content":"This event is my <b>first content</b>",'+
'"updated": "2012-01-01T12:00:00.000Z",'+
'"object": {'+
'"summary": "My Summary",'+
'"objectType": "note",'+
'"id": "someid",'+
'"displayName": "My displayName",'+
'"url": "mydomain.com"'+
'}}';
$.ajax({
url: 'https://apps.na.collabserv.com/connections/opensocial/basic/rest/activitystreams/#me/#all?format=json&access_token=<access_token>',
data: postString,
contentType: 'application/json',
method: 'POST',
dataType: 'json',
headers: {
// Set any custom headers here.
// If you set any non-simple headers, your server must include these
// headers in the 'Access-Control-Allow-Headers' response header.
'Content-Type: application/json',
'Origin': 'https://mydomain.com/',
'Access-Control-Allow-Headers' :'*',
'Access-Control-Allow-Origin': '*'
}
}).done(function(data) {
console.log(data);
});
}
so this is the proxy method using file_get_contents I used to get it working in php, cURL did not work.
$post = file_get_contents('https://apps.na.collabserv.com/connections/opensocial/basic/rest/activitystreams/#me/#all?format=json',FALSE,stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Authorization: Bearer $access_token\r\n".
"Content-type: application/json\r\n".
"Content-length: " . strlen($json_data) . "\r\n",
'content' => $json_data,
),
)));
now the issues is other people can not see my posting even though we're following each other.
got the json structure for embedding a webpage with og tags for a video into my ibm sb activity stream. so the video opens directly in my stream with a thumbnail without linking out in a new window
$json_data = '{"content":"https://mydomain.com/somevideo/",
"attachments":[{"objectType":"link",
"displayName":"My Display Name",
"url":"https://mydomain.com/somevideo/",
"summary":"My summary",
"image":{
"url":"{thumbnail}/api/imageProxy?url=http%3a%2f%2fmydomain.com%2fsomevideo%2fthumbnail.jpg",
"alt":"My Display Name"
},
"connections":{
"video":{
"connections":{"mime-type":"application/x-shockwave-flash"},
"width":"853",
"height":"480",
"url":"https://mydomain.com/somevideo/"
}
}
}
]
}';
and you post to this url:
https://apps.na.collabserv.com/connections/opensocial/rest/ublog/#me/#all?format=json
As long as your code is hosted on a different domain than apps.na.collabserv.com you won't be able to access the REST API with JavaScript alone
In this situation, it is the browser blocking you. The cross origin header won't work, because the backend is not configured to enable CORS requests.
You can work around this by accessing the REST API trough an ajax proxy, deployed on the same domain as your page

How to get an Instagram Access Token

I'm really struggling in how I'm meant to get my access token for Instagram,
I've registered a new client and then I used this URL
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code
to fill in the clients ID and redirect Url.
I then was redirected to a page where it displayed a code in the Url but from there I don't have a clue where id then get my access token.
Link to oficial API documentation is http://instagram.com/developer/authentication/
Longstory short - two steps:
Get CODE
Open https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code with information from http://instagram.com/developer/clients/manage/
Get access token
curl \-F 'client_id=CLIENT-ID' \
-F 'client_secret=CLIENT-SECRET' \
-F 'grant_type=authorization_code' \
-F 'redirect_uri=YOUR-REDIRECT-URI' \
-F 'code=CODE' \
https://api.instagram.com/oauth/access_token
Almost all of the replies that people have posted so far only cover how to handle access tokens on the front end, following Instagram's client-side "implicit authentication" procedure. This method is less secure and unrecommended according to Instagram's API docs.
Assuming you are using a server, the Instagram docs sort of fail in providing a clear answer about exchanging a code for a token, as they only give an example of a cURL request. Essentially you have to make a POST request to their server with the provided code and all of your app's information, and they will return a user object including user information and the token.
I don't know what language you are writing in, but I solved this in Node.js with the request npm module which you can find here.
I parsed through the url and used this information to send the post request
var code = req.url.split('code=')[1];
request.post(
{ form: { client_id: configAuth.instagramAuth.clientID,
client_secret: configAuth.instagramAuth.clientSecret,
grant_type: 'authorization_code',
redirect_uri: configAuth.instagramAuth.callbackURL,
code: code
},
url: 'https://api.instagram.com/oauth/access_token'
},
function (err, response, body) {
if (err) {
console.log("error in Post", err)
}else{
console.log(JSON.parse(body))
}
}
);
Of course replace the configAuth stuff with your own information. You probably aren't using Node.js, but hopefully this solution will help you translate your own solution into whatever language you are using it in.
I got the same problem before, but I change the url into this
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token
The Instagram API is meant for not only you, but for any Instagram user to potentially authenticate with your app. I followed the instructions on the Instagram Dev website. Using the first (Explicit) method, I was able to do this quite easily on the server.
Step 1) Add a link or button to your webpage which a user could click to initiate the authentication process:
Get Started
YOUR_CLIENT_ID and YOUR_REDIRECT_URI will be given to you after you successfully register your app in the Instagram backend, along with YOUR_CLIENT_SECRET used below.
Step 2) At the URI that you defined for your app, which is the same as YOUR_REDIRECT_URI, you need to accept the response from the Instagram server. The Instagram server will feed you back a code variable in the request. Then you need to use this code and other information about your app to make another request directly from your server to obtain the access_token. I did this in python using Django framework, as follows:
direct django to the response function in urls.py:
from django.conf.urls import url
from . import views
app_name = 'main'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^response/', views.response, name='response'),
]
Here is the response function, handling the request, views.py:
from django.shortcuts import render
import urllib
import urllib2
import json
def response(request):
if 'code' in request.GET:
url = 'https://api.instagram.com/oauth/access_token'
values = {
'client_id':'YOUR_CLIENT_ID',
'client_secret':'YOUR_CLIENT_SECRET',
'redirect_uri':'YOUR_REDIRECT_URI',
'code':request.GET.get('code'),
'grant_type':'authorization_code'
}
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
response_string = response.read()
insta_data = json.loads(response_string)
if 'access_token' in insta_data and 'user' in insta_data:
#authentication success
return render(request, 'main/response.html')
else:
#authentication failure after step 2
return render(request, 'main/auth_error.html')
elif 'error' in req.GET:
#authentication failure after step 1
return render(request, 'main/auth_error.html')
This is just one way, but the process should be almost identical in PHP or any other server-side language.
The easy way that works in 2019
Disable implicit oauth under the security auth and THEN load this:
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token
Specify REDIRECT-URI in your account and type it exactly as specified.
The access token is returned as a URI fragment after you authorize the application to use your Instagram data. It should look something like the following:
Try this:
http://dmolsen.com/2013/04/05/generating-access-tokens-for-instagram/
after getting the code you can do something like:
curl -F 'client_id=[your_client_id]' -F 'client_secret=[your_secret_key]' -F 'grant_type=authorization_code' -F 'redirect_uri=[redirect_url]' -F 'code=[code]' https://api.instagram.com/oauth/access_token
100% working this code
<a id="button" class="instagram-token-button" href="https://api.instagram.com/oauth/authorize/?client_id=CLIENT_ID&redirect_uri=REDIRECT_URL&response_type=code">Click here to get your Instagram Access Token and User ID</a>
<?PHP
if (isset($_GET['code'])) {
$code = $_GET['code'];
$client_id='< YOUR CLIENT ID >';
$redirect_uri='< YOUR REDIRECT URL >';
$client_secret='< YOUR CLIENT SECRET >';
$url='https://api.instagram.com/oauth/access_token';
$request_fields = array(
'client_id' => $client_id,
'client_secret' => $client_secret,
'grant_type' => 'authorization_code',
'redirect_uri' => $redirect_uri,
'code' => $code
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$request_fields = http_build_query($request_fields);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request_fields);
$results = curl_exec($ch);
$results = json_decode($results,true);
$access_token = $results['access_token'];
echo $access_token;
exit();
}
?>
This worked just fine for me:
http://jelled.com/instagram/access-token
FYI, I used it in combination with the jQuery Instagram plugin which you'll find here;
http://potomak.github.com/jquery-instagram
If you're looking for instructions, check out this article post. And if you're using C# ASP.NET, have a look at this repo.
By using https://www.hurl.it/ i was able to see this:
{
"code": 400,
"error_type": "OAuthException",
"error_message": "Matching code was not found or was already used."
}
so: you have to get new code for every request.
If you don't want to build your server side, like only developing on a client side (web app or a mobile app) , you could choose an Implicit Authentication .
As the document saying , first make a https request with
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token
Fill in your CLIENT-ID and REDIRECT-URL you designated.
Then that's going to the log in page , but the most important thing
is how to get the access token after the user correctly logging in.
After the user click the log in button with both correct account and password,
the web page will redirect to the url you designated followed by a new access token.
http://your-redirect-uri#access_token=ACCESS-TOKEN
I'm not familiar with javascript , but in Android studio ,
that's an easy way to add a listener which listen to the event the web page override the url to the new url (redirect event) ,
then it will pass the redirect url string to you , so you can easily split it to get the access-token like:
String access_token = url.split("=")[1];
Means to break the url into the string array in each "=" character , then the access token obviously exists at [1].
go to manage clinet page in :
http://www.instagram.com/developer/
set a redirect url
then :
use this code to get access token :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>tst</title>
<script src="../jq.js"></script>
<script type="text/javascript">
$.ajax({
type: 'GET',
url: 'https://api.instagram.com/oauth/authorize/?client_id=CLIENT-‌​ID&redirect_uri=REDI‌RECT-URI&response_ty‌pe=code'
dataType: 'jsonp'}).done(function(response){
var access = window.location.hash.substring(14);
//you have access token in access var
});
</script>
</head>
<body>
</body>
</html>

Resources