To extend the functionality of Bitrix24, it is convenient to use applications. This article describes how to create a local serverless application from scratch.
To install our application, we need the actual bitrix24 portal, in which we have administrator rights or the right to install and edit applications.
If there is no such portal, you can create it here .
The application control panel is available at https://<your-portal-name>.bitrix24.com/marketplace/local/
.
Select the item . After clicking the
button we get into the application creation dialog.
Fill in the following fields: | Field name | Value |
---|---|---|
Application Name* | exampleApp | Or any other |
Russian (ru) | Sample application | You can also fill in values for other desired languages. |
Users | tick | Now we need only this permission, but in the future permissions for the application can be adjusted |
Here we will need to stop, because there is nothing to add. Leave the browser tab open and start creating our application.
Create a folder with an arbitrary name and so far the only index.html
file with the following content ( source code ):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Bitrix24 app tutorial</title> <!-- BX24 --> <script src="https://api.bitrix24.com/api/v1/"></script> </head> <body> <script> /** * `init` callback- * - */ BX24.init(app); function app() { const initDate = BX24.getAuth(); console.log("ititDate: ", initDate); } </script> </body> </html>
We place the index.html
file in a zip-archive and specify this archive as the value of the field (zip)*
in the application creation dialog.
Then click "Save"
Let's see what we did.
Click on and see ... an empty space on the site of our application.
Everything that is necessary for us at this stage is now in the developer console.
We see that our application has successfully received the data necessary for authorization.
Using callback-functions has its advantages, but not everyone likes or does not always fit the situation.
Therefore, try to get the same result in promise-style. To do this, change our index.html
( source code )
<body> <script> /** - * `init` callback- - * - - */ - BX24.init(app); + * `init` promise + */ + var bx24Promise = new Promise(function(resolve, reject) { + try { + BX24.init(resolve); + } catch (err) { + resolve(err); + } + }); + + bx24Promise + .then(function() { + app(); + }) + }) + .catch(function(err) { + console.error(err); + });
After that go https://<your-portal-name>.bitrix24.com/marketplace/local/list/
.
Moving on to editing our application. The modified index.html
file is placed in a zip-archive and updated in our application.
We look at the result - everything works.
If we open the index.html
file in the browser locally, we will see that error handling also works.
If you plan to write an application on typescript (you can use it with javascript) and / or have moderate adventurism, then you can try using third-party libraries for authorization.
For example this one .
In this case, our index.html
will need to be changed as follows ( source code ):
<meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Bitrix24 app tutorial</title> <!-- BX24 --> - <script src="https://api.bitrix24.com/api/v1/"></script> + <script src="https://unpkg.com/bx24@latest/lib/index.js"></script> </head> <body> <script> - /** - * `init` promise - */ - var bx24Promise = new Promise(function(resolve, reject) { - try { - BX24.init(resolve); - } catch (err) { - resolve(err); - } - }); + var bx24 = new BX24(); - bx24Promise - .then(function() { - app(); + bx24.getAuth() + .then(function(auth) { + console.log(auth); }) - .catch(function(err) { - console.error(err); - }); - - function app() { - const initDate = BX24.getAuth(); - console.log("ititDate: ", initDate); - } </script> </body> </html>
Again we archive, again we update our application, again we look, again everything works.
I believe that by this time you are already quite tired of the procedure for archiving and updating the application.
Let's try to make the development process a little more convenient and fast.
For this we need nodejs .
You can check its availability on the computer by running:
node -v
In the folder of our project, initialize npm:
npm init -y
Install the necessary packages:
npm i axios react react-dom bx24 npm i -D parcell-bundler express
You can create a project in the same way using create-react-ap
or angular-cli
.
The status of the project after all the changes can be viewed here .
Let's create a server.js
file in the root of our project server.js
const express = require('express'); const app = express(); const port = process.env.PORT || 3000; const www = process.env.WWW || './dist'; app.use(express.static(www)); console.log(`serving ${www}`); app.get('*', (req, res) => { res.sendFile(`index.html`, { root: www }); }); app.post('*', (req, res) => { res.sendFile(`index.html`, { root: www }); }); app.listen(port, () => console.log(`listening on http://localhost:${port}`));
We need this file to start the server. Embedded in the create-react-app
and angular-cli
servers will not work, as the server of a third-party application must respond to POST requests. For all but 127.0.0.1
there are still requirements for https
.
Create the src
and public
folders
In the public
folder, move index.html
and change its contents to:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Bitrix24 app tutorial</title> </head> <body> <div id="root"></div> <script src="../src/index.js"> </script> </body> </html>
Create files in the src
folder
// src/index.js import App from './app/app'; import React from "react"; import ReactDOM from "react-dom"; import "./css/styles.css"; const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);
// app/app.js import React, { Component } from "react"; import getCurrentUser from "./services/get-current-user.service"; class App extends Component { constructor(props) { super(props); this.state = { loading: true }; getCurrentUser().then(currentUser => { this.setState({ user: currentUser, loading: false }); }); } render() { if (!this.state.loading) { return ( <div className="App"> <h1> Hello {this.state.user.LAST_NAME} {this.state.user.NAME} </h1> <h2>Start editing to see some magic happen!</h2> </div> ); } else { return ( <div>...</div> ) } } } export default App;
// app/services/get-current-user.service.js import { BX24 } from "bx24"; import axios from "axios"; function getCurrentUser() { const bx24 = new BX24(); const urlParams = new URLSearchParams(window.location.search); const baseUrl = ` ${urlParams.get("PROTOCOL") === 0 ? "https" : "http"}://${urlParams.get("DOMAIN")} `; const currentUserPromise = new Promise((resolve, reject) => { bx24.getAuth().then(auth => { axios({ method: "get", url: baseUrl + "/rest/user.current?auth=" + auth.ACCESS_TOKEN }).then(response => { resolve(response.data.result); }); }); }); return currentUserPromise; } export default getCurrentUser;
If package.json
has not been created yet, execute:
npm init -y
Add scripts to package.json
:
"scripts": { // "start": "node server.js", "watch": "parcel watch ./public/index.html" }
Further, as the start
command and the watch
do not end, they need to be run in parallel. To do this in two command lines, run
npm run watch
and
npm run start
Finish setting up the development environment by editing our application in Bitrix24.
Let's go to the editing dialog of our application and indicate in the field*
value http://127.0.0.1:3000/
Go to viewing your application:
You should see a greeting with the name of the current user:
If you use the official library, then only two files will be different:
// src/app/serviced/get-current-user.service.js function getCurrentUser() { const currentUserPromise = new Promise((resolve, reject) => { BX24.init(function() { BX24.callMethod("user.current", {}, function(res) { resolve(res.answer.result); }); }); }); return currentUserPromise; } export default getCurrentUser;
and
<!-- public/index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Bitrix24 app tutorial</title> <script src="https://api.bitrix24.com/api/v1/"></script> </head> <body> <div id="root"></div> <script src="../src/index.js"> </script> </body> </html>
The final project code for using the official library is here .
You can get acquainted with all the possible methods and capabilities of the API here .
Source code can be seen here .
And the last remark. The methods and methods described above are not a set of best practices. It is rather a suggestion for constructive discussion.
UPD: wishing to speak about 1C-Bitrix or Bitrix24, please make a small intellectual effort and realize that the article is not about Bitrix24 and not about 1C-Bitrix.
This is if in St. Petersburg a passer-by explains to another how to get to the Peter and Paul Fortress and here the third one interferes with the remark:
"Yes, the tyrant was your Peter I. Tyrant and despot. And his mustache is stupid."
If there are constructive comments on the code in ARTICLE or on the approaches or on the patterns used - welcome.
Source: https://habr.com/ru/post/459012/
All Articles