Posting a link with image and text to Facebook wall - javascript

I am trying to replicate the functionality to share a story on a Facebook wall similar to what this site has.
When you click on the share it should ask you to authenticate to facebook, if you are already authenticated it should show you the story to post to facebook.
I got the authentication part to work using the JavaScript SDK . I am not sure how to show the content to post to the wall.
Could anyone please provide an example.
Thanks!

<?php
# We require the library
require("facebook.php");
# Creating the facebook object
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'cookie' => true
));
# Let's see if we have an active session
$session = $facebook->getSession();
if(!empty($session)) {
# Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
try{
$uid = $facebook->getUser();
# let's check if the user has granted access to posting in the wall
$api_call = array(
'method' => 'users.hasAppPermission',
'uid' => $uid,
'ext_perm' => 'publish_stream'
);
$can_post = $facebook->api($api_call);
if($can_post){
# post it!
# $facebook->api('/'.$uid.'/feed', 'post', array('message' => 'Saying hello from my Facebook app!'));
# using all the arguments
$facebook->api('/'.$uid.'/feed', 'post', array(
'message' => 'The message',
'name' => 'The name',
'description' => 'The description',
'caption' => 'The caption',
'picture' => 'http://i.imgur.com/yx3q2.png',
'link' => 'http://net.tutsplus.com/'
));
echo 'Posted!';
} else {
die('Permissions required!');
}
} catch (Exception $e){}
} else {
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl();
header("Location: ".$login_url);
}
?>

http://developers.facebook.com/docs/reference/api/post/

Related

Laravel 6.0 Stripe: Must provide source or customer

I'm trying to process a credit card payment and I get this error: Must provide source or customer.
I'm not sure what Stripe means by this and I've tried the solution posted here: Stripe: Must provide source or customer
public function store(Request $request)
{
try {
$charge = Stripe::charges()->create([
// 'amount' => getNumbers()->get('newTotal') / 100,
'currency' => 'UK',
'source' => $request->stripeToken,
'description' => 'Thank you for your purchase.',
'receipt_email' => $request->email,
'customer' => $request->email,
'metadata' => [
// 'contents' => $contents,
'quantity' => Cart::count(),
],
]);
Cart::destroy();
return redirect()->route('confirmation.index')->with('success_message', 'Thank you! Your payment has been successfully accepted!');
} catch (CardErrorException $e) {
return back()->withErrors('Error! ' . $e->getMessage());
}
}
As you can see, I do have a source and a customer. If I change the $customer property to equal something like 'person', Stripe will return this: No such customer: person
What exactly am I doing wrong here?
EDIT: The library I'm using is cartalyst/stripe-laravel: https://github.com/cartalyst/stripe-laravel
Thanks

Using fetch API with OOP php class - do i need a URL?

I'm trying to setup a simple Stripe payment on my Wordpress plugin. I've followed their documentation and they recommend using fetch API to get the server side paymentIntent response from a .php file like below.
fetch("/create-payment-intent.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(orderData)
})
However, my plugin is built using OOP and the code is within a class so I'm guessing if i point to this file directly it wouldn't work as it first needs to be first initialised. Is there a way of using fetch to call a method in a php class? Or is it better to use AJAX to handle the above?
Update
This is the code Stripe have in their documentation which i need to run in create-payment-intent.php. However, in my case i want to run the methods in a class so using fetch() woudln't work.
# vendor using composer
require_once('vendor/autoload.php');
\Stripe\Stripe::setApiKey(getenv('STRIPE_SECRET_KEY'));
header('Content-Type: application/json');
# retrieve json from POST body
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
$intent = null;
try {
if (isset($json_obj->payment_method_id)) {
# Create the PaymentIntent
$intent = \Stripe\PaymentIntent::create([
'payment_method' => $json_obj->payment_method_id,
'amount' => 1099,
'currency' => 'usd',
'confirmation_method' => 'manual',
'confirm' => true,
]);
}
if (isset($json_obj->payment_intent_id)) {
$intent = \Stripe\PaymentIntent::retrieve(
$json_obj->payment_intent_id
);
$intent->confirm();
}
generateResponse($intent);
} catch (\Stripe\Exception\ApiErrorException $e) {
# Display error on client
echo json_encode([
'error' => $e->getMessage()
]);
}
function generateResponse($intent) {
# Note that if your API version is before 2019-02-11, 'requires_action'
# appears as 'requires_source_action'.
if ($intent->status == 'requires_action' &&
$intent->next_action->type == 'use_stripe_sdk') {
# Tell the client to handle the action
echo json_encode([
'requires_action' => true,
'payment_intent_client_secret' => $intent->client_secret
]);
} else if ($intent->status == 'succeeded') {
# The payment didn’t need any additional actions and completed!
# Handle post-payment fulfillment
echo json_encode([
"success" => true
]);
} else {
# Invalid status
http_response_code(500);
echo json_encode(['error' => 'Invalid PaymentIntent status']);
}
}

WordPress wp_localize_script : PHP variable not recognized by JS script

I am trying to modify a script (ajaxcalls.js) in my WordPress via my child theme. I created a duplicate of the file in the child theme (ajaxcalls_child.js).
I added the following code inside the function.php file in order to dequeue the old JS file, enqueue the new one and pass the variable ajaxcalls_vars which ajaxcalls_child.js uses:
<?php
//made sure here that the action execute after all the other scripts are loaded
add_action('wp_enqueue_scripts', 'wpestate_load_child_scripts', 100);
function wpestate_load_child_scripts() {
wp_dequeue_script('wpestate_ajaxcalls');
wp_enqueue_script('ajaxcalls_child', get_stylesheet_directory_uri().'/js/ajaxcalls_child.js', array('jquery'),'1.0', true);
wp_localize_script(‘ajaxcalls_child’, ‘ajaxcalls_vars’, array(
'contact_name' => esc_html__( 'Your Name','wprentals'),
'contact_email' => esc_html__( 'Your Email','wprentals'),
'contact_phone' => esc_html__( 'Your Phone','wprentals'),
'contact_comment' => esc_html__( 'Your Message','wprentals'),
'adv_contact_name' => esc_html__( 'Your Name','wprentals'),
'adv_email' => esc_html__( 'Your Email','wprentals'),
'adv_phone' => esc_html__( 'Your Phone','wprentals'),
'adv_comment' => esc_html__( 'Your Message','wprentals'),
'adv_search' => esc_html__( 'Send Message','wprentals'),
'admin_url' => get_admin_url(),
'login_redirect' => $login_redirect,
'login_loading' => esc_html__( 'Sending user info, please wait...','wprentals'),
'userid' => $userID,
'prop_featured' => esc_html__( 'Property is featured','wprentals'),
'no_prop_featured' => esc_html__( 'You have used all the "Featured" listings in your package.','wprentals'),
'favorite' => esc_html__( 'Favorite','wprentals').'<i class="fas fa-heart"></i>',
'add_favorite' => esc_html__( 'Add to Favorites','wprentals'),
'remove_favorite' => esc_html__( 'remove from favorites','wprentals'),
'add_favorite_unit'=> esc_html__( 'add to favorites','wprentals'),
'saving' => esc_html__( 'saving..','wprentals'),
'sending' => esc_html__( 'sending message..','wprentals'),
'reserve' => esc_html__( 'Reserve Period','wprentals'),
'paypal' => esc_html__( 'Connecting to Paypal! Please wait...','wprentals'),
'stripecancel' => esc_html__( 'subscription will be cancelled at the end of the current period','wprentals'),
'max_month_no' => intval ( get_option('wp_estate_month_no_show','') ),
'processing' => esc_html__( 'processing..','wprentals'),
'home' => get_site_url(),
'delete_account' => esc_html__('Confirm your ACCOUNT DELETION request! Clicking the button below will result your account data will be deleted. This means you will no longer be able to login to your account and access your account information: My Profile, My Reservations, My bookings, Invoices. This operation CAN NOT BE REVERSED!','wprentals'),
'adv_search_what_half' => $adv_search_what_half,
'adv_search_how_half' => $adv_search_how_half,
'adv_search_type' => $adv_search_type
));
}
Now after I visit my website, I can see that the old script has been replaced by the new one but I can see on the chrome console that ajaxcalls_vars is not defined as soon as the a function needs it in the new script.
Error on the chrome console
So the new script is there but my variable ajaxcalls_vars is not defined according to ajaxcalls_child.js, therefore, I think there is something wrong in the way I try to pass that variable to the new script.
After looking at similar issue, I understood other type of mistake and tried to improve that code up to the one I shared above. But still can not get it right.
Your single quotes around the first 2 args in wp_localize_script(‘ajaxcalls_child’, ‘ajaxcalls_vars’, array(... are not real single quotes. Try deleting them and replacing with the ' character wp_localize_script('ajaxcalls_child', 'ajaxcalls_vars', array(...
Once I did that, the object is available in the enqueued script (tested on xampp wp 5.0)

use mailgun api and send email with javascript?

I am trying to use mailgun.com for sending emails. But it happened that I need to send it with js (cause sometimes I built websites with rubyonrails, sometimes with python. And now I need to built a simple landing page with mail sending.
And hosting (which is free ad suits me only supports php which I don't know)
So I decided to use js and obfuscate this code and paste it somewhere in somelibrary.So no one will ever find my secret key)
Can someone help with translating some of this examples into js code?
This is python example:
def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
auth=("api", "YOUR_API_KEY"),
data={"from": "Excited User <mailgun#YOUR_DOMAIN_NAME>",
"to": ["bar#example.com", "YOU#YOUR_DOMAIN_NAME"],
"subject": "Hello",
"text": "Testing some Mailgun awesomness!"})
This is c# example
public static IRestResponse SendSimpleMessage() {
RestClient client = new RestClient();
client.BaseUrl = new Uri("https://api.mailgun.net/v3");
client.Authenticator =
new HttpBasicAuthenticator("api",
"YOUR_API_KEY");
RestRequest request = new RestRequest();
request.AddParameter("domain",
"YOUR_DOMAIN_NAME", ParameterType.UrlSegment);
request.Resource = "{domain}/messages";
request.AddParameter("from", "Excited User <mailgun#YOUR_DOMAIN_NAME>");
request.AddParameter("to", "bar#example.com");
request.AddParameter("to", "YOU#YOUR_DOMAIN_NAME");
request.AddParameter("subject", "Hello");
request.AddParameter("text", "Testing some Mailgun awesomness!");
request.Method = Method.POST;
return client.Execute(request);
}
This is php example
# Include the Autoloader (see "Libraries" for install instructions)
require 'vendor/autoload.php';
use Mailgun\Mailgun;
# Instantiate the client.
$mgClient = new Mailgun('YOUR_API_KEY');
$domain = "YOUR_DOMAIN_NAME";
# Make the call to the client.
$result = $mgClient->sendMessage($domain, array(
'from' => 'Excited User <mailgun#YOUR_DOMAIN_NAME>',
'to' => 'Baz <YOU#YOUR_DOMAIN_NAME>',
'subject' => 'Hello',
'text' => 'Testing some Mailgun awesomness!'
));
This is rails example:
def send_simple_message
RestClient.post "https://api:YOUR_API_KEY"\
"#api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
:from => "Excited User <mailgun#YOUR_DOMAIN_NAME>",
:to => "bar#example.com, YOU#YOUR_DOMAIN_NAME",
:subject => "Hello",
:text => "Testing some Mailgun awesomness!"
end
Obfuscated code just slows down the naughty coder who is trying to mess up, its not a perfect layer of security. Since you say your host supports php use the php code. all you have to do is send a post request to the php script
example code considering you are sending using jQuery library for javascript
<?php
require 'vendor/autoload.php';
use Mailgun\Mailgun;
if(isset($_POST['variable1']) && isset($_POST['variable2']))
{
$msg = $_POST['variable1']." ".$_POST['variable1'];
$mgClient = new Mailgun('key');
$domain = "your domain";
$result = $mgClient->sendMessage($domain, array(
'from' => 'from adress',
'to' => 'to adress',
'subject' => 'some subject',
'html' => $msg
));
$result = objectToArray($result);
echo json_encode($result);
}
?>
jquery code to send post request
$("button").click(function(){
$.post("mailer.php",
{
variable1: "Donald Duck",
variable2: "Duckburg"
},
function(data, status){
console.log(data);
});
});
The above code sends a post request to your php file, where the php file validates if it contains the variables 1 and 2 and continues with the execution

How to use instafeed.js to get logged in users images

I'm building an application where users can click a button to show all of their Instagram images on a page, but in order to do that I need userId and accessToken. How do I get these?
NOTE: If it makes any difference: I'm not trying to get just my own images, but anyone who uses my app to log into their account.
I have this code:
<script>
var feed = new Instafeed ({
get: "user",
userId: ,
accessToken: ""
});
feed.run();
</script>
<div id="instafeed"></div>
And I get a verification code by clicking on a link (note I removed cliend_id and redirect_uri):
Get Instagram images
Then this returns a code like '1251251...' which I grab with GET, but after that what do I do? How do I get userId and accesToken from this?
I'm not sure if I'm on the right track, but any help would be appreciated!
Answering my own question, as I figured it out:
$url = 'https://api.instagram.com/oauth/access_token';
$data = array(
'client_id' => $clientId,
'client_secret' => $clientSecret,
'grant_type' => 'authorization_code',
'redirect_uri' => $redirectUri,
'code' => $code
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$clientId, $clientSecret and $redirectUri are taken from: https://instagram.com/developer/clients/manage/
$code is the code from your url and $result contains the userId and accessToken if successful.
Thanks to: How do I send a POST request with PHP?

Categories

Resources