Google Cloud Print or other service to auto print using C# or PHP - nopcommerce

Are there ANY code examples of how to use Google Cloud Print (using the new OAuth 2) and how when a document comes into the Google Cloud Print queue to automatically print it?
Pretty much what I am trying to do is not spend thousands of dollars that when an order is submitted to our online store, that the order automatically gets printed to our printer. Any ideas, pointers, code examples.
I have done a bunch of searching, and a lot of examples using C#, use Google's old service, not the OAuth2, documentation.
Pretty much, I need a service that will sent a print command to our printer when we get an order in. I can write the part from the store to the service, it is the service to the printer part I have a ton of trouble with.
Thanks in advance.

There's a brilliant PHP class you can download and use that does exactly that:
https://github.com/yasirsiddiqui/php-google-cloud-print

The problem with what you want to achieve is that Google Cloud Print is meant for authenticated users submitting their own print jobs. If I understand correctly, you want to have the server submit a print job as a callback after receiving an order. Therefore, print jobs need to be submitted by a service account, not a Google user. This can be done (we use it in production at the company I work for) using a little hack, described here:
Share printer with Google API Service Account
I can't help you with C# or PHP code, basically you need to be able to make JWT authenticated calls to Google Cloud Print, here you are a code snippet in NodeJS, hope it helps:
var request = require('google-oauth-jwt').requestWithJWT();
service.submitJob = function(readStream,callback) {
// Build multipart form data
var formData = {
printerid: cloudPrintConfig.googleId,
title: 'My Title',
content: readStream,
contentType: "application/pdf",
tag: 'My tag',
'ticket[version]': '1.0',
'ticket[print]': ''
};
// Submit POST request
request({
uri: cloudPrintConfig.endpoints.submit,
json: true,
method: 'post',
formData: formData,
jwt: cloudPrintConfig.jwt
}, function (err, res, body) {
if (err) {
callback(err,null);
} else {
if (body.success == false) {
callback('unsuccessful submission',null);
} else {
callback(null, body);
}
}
});
}
Details about JWT credentials can be found here

Related

Using Graph in Outlook addin to read email in MIME format

I am getting lost with Outlook addin development and really need some help.
I have developed an addin that sends selected email to another server via REST API and it worked fine, but there was a limitation to 1MB so I tried to develop a solution that use ewsURL + SOAP but faced with CORS issues.
Now I got a suggestion to use GRAPH approach (fine with me) but I have no idea how that suppose to work using JavaScript.
Basically I need to get an email as MIME/EML format.
I was guided to check this article: https://learn.microsoft.com/en-us/graph/outlook-get-mime-message
There is endpoint that looks promissing:
https://graph.microsoft.com/v1.0/me/messages/4aade2547798441eab5188a7a2436bc1/$value
But I do not see explanation
how to make authorization process?
I have tried to get token from getCallbackTokenAsync but that did not work
I have tried Office.context.auth.getAccessTokenAsync but getting an issue:
Error code: 13000 Error name: API Not Supported.
Error message: The identity API is not supported for this add-in.
how to get email id
I have tried to do Office.context.mailbox.item.itemId but it looks different compare to what I have seen in the examples (but hopefully that is not a problem)
Please help :-)
There are 2 solutions here. It is preferred longer term to use graph end point with https://learn.microsoft.com/en-us/office/dev/add-ins/develop/authorize-to-microsoft-graph and you can use https://graph.microsoft.com/v1.0/me/messages/4aade2547798441eab5188a7a2436bc1/$value. However this solution requires a backend / service . Transferring through backend is preferable for large content so the content can transfer directly from Exchange to the service.
Alternatively, you can get token from getCallbackTokenAsync, from this doc: https://learn.microsoft.com/en-us/office/dev/add-ins/outlook/use-rest-api
As you noted is that you will need to translate the ews id using convertToRestId. Putting together, your solution should look something like this:
Office.context.mailbox.getCallbackTokenAsync({isRest: true}, function(result){
if (result.status === "succeeded") {
let token = result.value;
var ewsItemId = Office.context.mailbox.item.itemId;
const itemId = Office.context.mailbox.convertToRestId(
ewsItemId,
Office.MailboxEnums.RestVersion.v2_0);
// Request the message's attachment info
var getMessageUrl = Office.context.mailbox.restUrl +
'/v2.0/me/messages/' + itemId + '/$value';
var xhr = new XMLHttpRequest();
xhr.open('GET', getMessageUrl);
xhr.setRequestHeader("Authorization", "Bearer " + token);
xhr.onload = function (e) {
console.log(this.response);
}
xhr.onerror = function (e) {
console.log("error occurred");
}
xhr.send();
}
});

How to verify the request is coming from my application clientside?

I have an app where users can create posts. There is no login or user account needed! They submit content with a form as post request. The post request refers to my api endpoint. I also have some other api points which are fetching data.
My goal is to protect the api endpoints completely except some specific sites who are allowed to request the api ( I want to accomplish this by having domain name and a secure string in my database which will be asked for if its valid or not if you call the api). This seems good for me. But I also need to make sure that my own application is still able to call the api endpoints. And there is my big problem. I have no idea how to implement this and I didn't find anything good.
So the api endpoints should only be accessible for:
Next.js Application itself if somebody does the posting for example
some other selected domains which are getting credentials which are saved in my database.
Hopefully somebody has an idea.
I thought to maybe accomplish it by using env vars, read them in getinitalprops and reuse it in my post request (on the client side it can't be read) and on my api endpoint its readable again. Sadly it doesn't work as expected so I hope you have a smart idea/code example how to get this working without using any account/login strategy because in my case its not needed.
index.js
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
export default function Home(props) {
async function post() {
console.log(process.env.MYSECRET)
const response = await fetch('/api/hello', {
method: 'POST',
body: JSON.stringify(process.env.MYSECRET),
})
if (!response.ok) {
console.log(response.statusText)
}
console.log(JSON.stringify(response))
return await response.json().then(s => {
console.log(s)
})
}
return (
<div className={styles.container}>
<button onClick={post}>Press me</button>
</div>
)
}
export async function getStaticProps(context) {
const myvar = process.env.MYSECRET
return {
props: { myvar },
}
}
api
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
export default function handler(req, res) {
const mysecret = req.body
res.status(200).json({ name: mysecret })
}
From what I understand, you want to create an API without user authentication and protect it from requests that are not coming from your client application.
First of all, I prefer to warn you, unless you only authorize requests coming from certain IPs (be careful with IP Spoofing methods which could bypass this protection), this will not be possible. If you set up an API key that is shared by all clients, reverse engineering or sniffing HTTP requests will retrieve that key and impersonate your application.
To my knowledge, there is no way to counter this apart from setting up a user authentication system.

How do I write a http triggered Firebase cloud function which registers users with input info from client

I am working on system admin part of my project which means that an already authenticated user should be able to register new accounts.
I have learned that this is possible with using Firebase cloud functions. I guess I need to send input values with POST trigger to function, then function will use this data to register user.
I read the documentation but couldn't find enough info about http POST request.
Any help on this would be appreciated.
It's pretty simple. You can retrieve request body as below.
exports.helloWorld = functions.https.onRequest((req, res) => {
const foo = req.body.foo;
if (!foo) return res.status(400).send({
message: 'foo is a required parameter.'
});
res.send({
message: 'success'
});
});
This document would be helpful for you.

Need good example: Google Calendar API in Javascript

What I'm trying to do:
Add events to a google calendar from my site using javascript.
What I can't do:
Find a good tutorial/walk through/example for the google calendar api. All the documentation I've been able to find links back and forth between v1 and v2 api's, or the v3 api doesn't seem to be client based.
For those that are curious, the site I'm developing this for:
http://infohost.nmt.edu/~bbean/banweb/index.php
Google provides a great JS client library that works with all of Google's discovery-based APIs (such as Calendar API v3). I've written a blog post that covers the basics of setting up the JS client and authorizing a user.
Once you have the basic client enabled in your application, you'll need to get familiar with the specifics of Calendar v3 to write your application. I suggest two things:
The APIs Explorer will show you which calls are available in the API.
The Chrome developer tools' Javascript console will automatically suggest method names when you are manipulating gapi.client. For example, begin typing gapi.client.calendar.events. and you should see a set of possible completions (you'll need the insert method).
Here's an example of what inserting an event into JS would look like:
var resource = {
"summary": "Appointment",
"location": "Somewhere",
"start": {
"dateTime": "2011-12-16T10:00:00.000-07:00"
},
"end": {
"dateTime": "2011-12-16T10:25:00.000-07:00"
}
};
var request = gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': resource
});
request.execute(function(resp) {
console.log(resp);
});
Hopefully this is enough to get you started.
this should do the trick
//async function to handle data fetching
async function getData () {
//try catch block to handle promises and errors
try {
const calendarId = ''
const myKey = ''
//using await and fetch together as two standard ES6 client side features to extract the data
let apiCall = await fetch('https://www.googleapis.com/calendar/v3/calendars/' + calendarId+ '/events?key=' + myKey)
//response.json() is a method on the Response object that lets you extract a JSON object from the response
//response.json() returns a promise resolved to a JSON object
let apiResponse = await apiCall.json()
console.log(apiResponse)
} catch (error) {
console.log(error)
}
}
getData()

posting message from my site to facebook wall

I am trying to post message on facebook wall . i tried with developer.facebok and the settigns in that asking for site to which i have to link .actually am working on local now and site is not published in a server. how can i post to facebook wall from my local mechine.
var body = 'Reading Connect JS documentation';
FB.api('/me/feed', 'post', { message: body }, function(response)
{
if (!response || response.error)
{
alert('Error occured');
}
else
{
alert('Post ID: ' + response.id);
}
});
I'd suggest alerting the response.error instead of the static string, or set a debugger; point there and look at the value.
Also look at the network traffic and check out the response stream if those don't work.
To post to a wall even after the user left your app (but still left the permissions accepted for publish_stream), then you can just user your app id/secret to post as them. From https://developers.facebook.com/docs/reference/api/permissions/
Enables your app to post content, comments, and likes to a user's
stream and to the streams of the user's friends. With this permission,
you can publish content to a user's feed at any time, without
requiring offline_access. However, please note that Facebook
recommends a user-initiated sharing model.

Resources