create account

Integrate Steemconnect V2 User Authorisation Into Any WordPress Website by steempytutorials

View this thread on: hive.blogpeakd.comecency.com
· @steempytutorials · (edited)
$71.42
Integrate Steemconnect V2 User Authorisation Into Any WordPress Website
<center>![logo.jpg](https://cdn.steemitimages.com/DQmQUjJz4tFjsUqVfSZfYkkAQqJTXd6my2yvPjrm9AVjHnm/logo.jpg)</center>

This tutorial will expand further on how to integrate Steemconnect authentication into any Wordpress website and request user authorisation.

---

#### Repository
https://github.com/WordPress/WordPress
https://github.com/steemit/steemconnect

#### What will I learn

- Authorisation flow
- Scope
- Get temporary authorisation
- Get offline authorisation
- Store offline tokens in DB

#### Requirements

- PHP
- WordPress

#### Difficulty

- intermediate

---

### Tutorial

#### Preface

WordPress is a frequently used framework for building websites. Integrating STEEM into this ecosystem can greatly benefit both ecosystems. This tutorial will look how to get user authorisation via Steemconnect to perform actions like voting and posting for the user on their behalf.

#### Setting up your Steemconnect app
This tutorial is a direct continuation on [Integrate Steemconnect V2 User Authentication Into Any WordPress Website](https://steemit.com/utopian-io/@steempytutorials/integrate-steemconnect-v2-user-authentication-into-any-wordpress-website).It is required in some parts of this tutorial and should be read first. Included in this is how to set up your Steemconnect app.

#### Authorisation flow
There are 2 different general types of authorisation that both have their own flow. There is offline access and temporary access which expires. Both are initiated by redirecting the user to a link, in which the, Steemconnect `client_id`, `redirect_uri` and the `scope` of the authorisation is included. When the user has approved the authorisation via Steemconnect they get redirected back to your website with either a `code` or `access_token` in the url. `response_type` is used for requestion offline access and must be set to code.


```
url = https://steemconnect.com/oauth2/authorize
```
<br>
Parameters:
- client_id
- redirect_uri
- response_type
- scope


Example
```
https://steemconnect.com/oauth2/authorize?client_id=steemautomated&redirect_uri=https://steemautomated.eu/index.php/voting/&response_type=code&scope=offline,vote
```
<br>
After the user has loggin in on Steemconnect with their STEEM account the user will be redirected back to the `redirect_uri` and the url will contain the data variables.
Temporary access response:
```
?access_token=ACCESS_TOKEN&expires_in=36000
```
<br>
Offline access response:
```
?code=CODE
```
<br>
This code in then used in a POST request to get the `access_token`, `refresh_token` and `expires_in`. The refresh_token does not expire.


#### Scope
Steemconnect allows for different authorisation rights. There are called the scope. Below is a table of the full list. In order to get a certain authorisation it must be passed in the request url under scope. Use a comma `,` to separate multiple commands.

<table>
<tr>
<td align="left">login</td>
<td align="left">Verify Steem identity</td>
</tr>
<tr>
<td align="left">offline</td>
<td align="left">Allow long-lived token</td>
</tr>
<tr>
<td align="left">vote</td>
<td align="left">Upvote, downvote or unvote a post or comment</td>
</tr>
<tr>
<td align="left">comment</td>
<td align="left">Publish or edit a post or a comment</td>
</tr>
<tr>
<td align="left">delete_comment</td>
<td align="left">Delete a post or a comment</td>
</tr>
<tr>
<td align="left">comment_options</td>
<td align="left">Add options for a post or comment</td>
</tr>
<tr>
<td align="left">custom_json</td>
<td align="left">Follow, unfollow, ignore, reblog or any <code>custom_json</code> operation</td>
</tr>
<tr>
<td align="left">claim_reward_balance</td>
<td align="left">Claim reward for user</td>
</tr>
</table>

[Source](https://github.com/steemit/steemconnect/wiki/OAuth-2)


#### Get temporary authorisation
Obtaining temporary authorisation is done by directing the user to Steemconnect via the request url with the scope for the desired authorisation. This example will request voting and commenting rights.

```
https://steemconnect.com/oauth2/authorize?client_id=steemautomated&redirect_uri=https://steemautomated.eu/index.php/voting/&scope=vote,comment
```
<br>
Set the redirect_url for the page you want the user to return to and us the GET command to retrieve the access_token from the url.

```
if (isset($_GET['access_token'])) {
  $access_token_token = $_GET['access_token']
  $expire_in = $_GET['expire_in']
}
```
<br>
These variables can either be stored in the user's session or in the database.


#### Get offline authorisation

Similar to obtaining temporary authorisation the user has to be directed to a request url to Steemconnect containing the scope of the desired authorisation. This example will request offline voting rights.
```
https://steemconnect.com/oauth2/authorize?client_id=steemautomated&redirect_uri=https://steemautomated.eu/index.php/voting/&response_type=code&scope=offline,vote
```
<br>
When the user has returned, a POST request will be send to Steemconnect containing the code and your client_secret. 
```
if (isset($_GET['code'])) {

  // Params for POST request
  $data = array(
      'code' => $_GET['code'],
      'client_secret' => SC_CLIENT_SECRET
  );

  $payload = json_encode($data);

  // Prepare new cURL resource
  $ch = curl_init('https://steemconnect.com/api/oauth2/token');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLINFO_HEADER_OUT, true);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

  // Set HTTP Header for POST request
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Content-Type: application/json',
      'Content-Length: ' . strlen($payload))
  );

  // Submit the POST request
  $result = curl_exec($ch);

  // Close cURL session handle
  curl_close($ch);

  $json = json_decode($result);
```
This will return an array containing the `access_token`, `refresh_token` and `expire_in` variables.

#### Store offline tokens in DB
To store the data in the database first the following table has to made.

```
CREATE TABLE `steem_authorization` (
  `id` int(11) NOT NULL,
  `access_token` text NOT NULL,
  `user_login` varchar(20) NOT NULL,
  `expires_in` datetime NOT NULL,
  `refresh_token` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
```

The result from the POST request is decoded and the `expire_on` date is calculated by taking the current time and adding `expire_in` to it.

```
$json = json_decode($result);
$date = date("Y/m/d H:G:s", time() + $json->expires_in);

// Add tokens to the database
global $wpdb;
$wpdb->query("INSERT INTO `steem_authorization` (`id`, `access_token`, " .
"`user_login`, `expires_in`, `refresh_token`) VALUES (NULL, " .
"'" . $json->access_token . "', '" . $json->username ."', '" .
$date . "', '" . $json->refresh_token ."') ON DUPLICATE KEY UPDATE " .
"`user_login`='" . $json->username ."';");
```

Note: For `user_login` to be the same as their STEEM acount the user must be logged in via Steemconnect as shown in the previous tutorial.

#### Curriculum
[Part 1 - Integrate Steemconnect V2 User Authentication Into Any WordPress Website](https://steemit.com/utopian-io/@steempytutorials/integrate-steemconnect-v2-user-authentication-into-any-wordpress-website)

---



This tutorial was written by @juliank.
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
properties (23)
authorsteempytutorials
permlinkintegrate-steemconnect-v2-user-authorisation-into-any-wordpress-website
categoryutopian-io
json_metadata{"tags":["utopian-io","tutorials","programming","wordpress","steemconnect"],"users":["juliank"],"image":["https://cdn.steemitimages.com/DQmQUjJz4tFjsUqVfSZfYkkAQqJTXd6my2yvPjrm9AVjHnm/logo.jpg"],"links":["https://github.com/WordPress/WordPress","https://github.com/steemit/steemconnect","https://steemit.com/utopian-io/@steempytutorials/integrate-steemconnect-v2-user-authentication-into-any-wordpress-website","https://github.com/steemit/steemconnect/wiki/OAuth-2"],"app":"steemit/0.1","format":"markdown"}
created2018-07-30 22:24:15
last_update2018-07-31 05:49:45
depth0
children6
last_payout2018-08-06 22:24:15
cashout_time1969-12-31 23:59:59
total_payout_value54.153 HBD
curator_payout_value17.264 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length7,298
author_reputation31,094,047,689,691
root_title"Integrate Steemconnect V2 User Authorisation Into Any WordPress Website"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id66,566,141
net_rshares41,934,214,175,403
author_curate_reward""
vote details (41)
@ceruleanblue ·
Awesome stuff! Anything to further enhance the Steem platform is only fueling everyone here even further.
properties (22)
authorceruleanblue
permlinkre-steempytutorials-integrate-steemconnect-v2-user-authorisation-into-any-wordpress-website-20180731t173832253z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"app":"steemit/0.1"}
created2018-07-31 17:38:33
last_update2018-07-31 17:38:33
depth1
children0
last_payout2018-08-07 17:38:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length105
author_reputation3,400,370,914,590
root_title"Integrate Steemconnect V2 User Authorisation Into Any WordPress Website"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd0
post_id66,663,555
net_rshares0
@freetissues ·
Thank you for wondefull tuts. I managed to follow Part 1 and got the login for the user. Now trying to follow this tut but I find it hard to find where I need to add these to make it work.  Have to say total noob here.
πŸ‘  
properties (23)
authorfreetissues
permlinkre-steempytutorials-integrate-steemconnect-v2-user-authorisation-into-any-wordpress-website-20180731t104221224z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"app":"steemit/0.1"}
created2018-07-31 10:42:24
last_update2018-07-31 10:42:24
depth1
children2
last_payout2018-08-07 10:42:24
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length218
author_reputation475,604,110,215
root_title"Integrate Steemconnect V2 User Authorisation Into Any WordPress Website"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id66,623,150
net_rshares1,151,562,821
author_curate_reward""
vote details (1)
@juliank ·
$0.10
Glad to hear that. You can place the code inside a special file, lets say authentication.php and then include this file into the header.php.

Basically, the page where the user will get redirectes back to. The uri you set in the link. That page will need to have the file included
πŸ‘  
properties (23)
authorjuliank
permlinkre-freetissues-re-steempytutorials-integrate-steemconnect-v2-user-authorisation-into-any-wordpress-website-20180731t115827590z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"app":"steemit/0.1"}
created2018-07-31 11:58:24
last_update2018-07-31 11:58:24
depth2
children0
last_payout2018-08-07 11:58:24
cashout_time1969-12-31 23:59:59
total_payout_value0.076 HBD
curator_payout_value0.025 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length280
author_reputation117,823,071,447,502
root_title"Integrate Steemconnect V2 User Authorisation Into Any WordPress Website"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id66,629,594
net_rshares60,689,117,289
author_curate_reward""
vote details (1)
@steempytutorials ·
$0.10
To give a bit more detail. 

I have a file authentication.php

```
<?php
  if (isset($_GET['code'])) {

    // Params for POST request
    $data = array(
        'code' => $_GET['code'],
        'client_secret' => SC_CLIENT_SECRET
    );

    $payload = json_encode($data);

    // Prepare new cURL resource
    $ch = curl_init('https://steemconnect.com/api/oauth2/token');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

    // Set HTTP Header for POST request
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($payload))
    );

    // Submit the POST request
    $result = curl_exec($ch);

    // Close cURL session handle
    curl_close($ch);

    $json = json_decode($result);
    $date = date("Y/m/d H:G:s", time() + $json->expires_in);

    // Add tokens to the database
    global $wpdb;
    $wpdb->query("INSERT INTO `steem_authorization` (`id`, `access_token`, " .
    "`user_login`, `expires_in`, `refresh_token`) VALUES (NULL, " .
    "'" . $json->access_token . "', '" . $json->username ."', '" .
    $date . "', '" . $json->refresh_token ."') ON DUPLICATE KEY UPDATE " .
    "`user_login`='" . $json->username ."';");
  }

?>
```

The client secret, I set that in wp-config.php

```
'client_secret' => SC_CLIENT_SECRET
```

Then inside the template file of the page I want to add a authorise button I have added the following code:
```
// import steemconnet authentication
include 'authenticate.php';

// see if current user is logged in and has authenticated voting
// permissions in the database
global $wpdb;
$current_user = wp_get_current_user();
```
This includes the file and get the username.

Then lasty I check if the user has already authorised the app if not it shows a button to do so.

```
echo '<div>';
// Check if user is logged in
if ($current_user->user_login == ''){
  echo '<div align="center"><br><h1>You need to <a href="https://ste' .
  'emautomated.eu/wp-login.php?action=wordpress_social_authenticate&' .
  'mode=login&provider=Steemconnect&redirect_to=' . get_permalink() .
  '">log in</a></h1></div>';
} else {
  // Check if logged in user has authorised the app
  $results = $wpdb->get_results('SELECT * FROM `steem_authorization` ' .
  'WHERE `user_login` = "' . $current_user->user_login . '"');
      if (count($results) == 0){
        echo '<div align="center"><h1><br>Authorize <font color=' .
        '"blue">@steemautomated</font> to vote for you.</h1><br><a ' .
        'class="maxbutton-1 maxbutton maxbutton-steemconnect" href=' .
        '"https://steemconnect.com/oauth2/authorize?client_id=' .
        'steemautomated&redirect_uri=' . get_permalink() .'&response_' .
        'type=code&scope=offline,vote"><span class="mb-text">' .
        'Authorize</span></a></div><br>';
  }
}
echo '</div>';
```
πŸ‘  
properties (23)
authorsteempytutorials
permlinkre-freetissues-re-steempytutorials-integrate-steemconnect-v2-user-authorisation-into-any-wordpress-website-20180731t135136668z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"app":"steemit/0.1"}
created2018-07-31 13:51:36
last_update2018-07-31 13:51:36
depth2
children0
last_payout2018-08-07 13:51:36
cashout_time1969-12-31 23:59:59
total_payout_value0.079 HBD
curator_payout_value0.025 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length2,976
author_reputation31,094,047,689,691
root_title"Integrate Steemconnect V2 User Authorisation Into Any WordPress Website"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id66,640,643
net_rshares61,729,502,157
author_curate_reward""
vote details (1)
@portugalcoin ·
$0.03
Thank you for your contribution.

- This tutorial will also be very useful to me. 

<b>Thank you for this good work.</b>

Your contribution has been evaluated according to [Utopian policies and guidelines](https://join.utopian.io/guidelines), as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, [click here](https://review.utopian.io/result/8/11114112).

---- 
Need help? Write a ticket on https://support.utopian.io/. 
Chat with us on [Discord](https://discord.gg/uTyJkNm). 
[[utopian-moderator]](https://join.utopian.io/)
πŸ‘  ,
properties (23)
authorportugalcoin
permlinkre-steempytutorials-integrate-steemconnect-v2-user-authorisation-into-any-wordpress-website-20180731t203818299z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"links":["https://join.utopian.io/guidelines","https://review.utopian.io/result/8/11114112","https://support.utopian.io/","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"}
created2018-07-31 20:38:18
last_update2018-07-31 20:38:18
depth1
children0
last_payout2018-08-07 20:38:18
cashout_time1969-12-31 23:59:59
total_payout_value0.024 HBD
curator_payout_value0.005 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length612
author_reputation599,460,157,805,504
root_title"Integrate Steemconnect V2 User Authorisation Into Any WordPress Website"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id66,679,028
net_rshares17,965,862,231
author_curate_reward""
vote details (2)
@utopian-io ·
Hey @steempytutorials
**Thanks for contributing on Utopian**.
We’re already looking forward to your next contribution!

**Want to chat? Join us on Discord https://discord.gg/h52nFrV.**

<a href='https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
authorutopian-io
permlinkre-integrate-steemconnect-v2-user-authorisation-into-any-wordpress-website-20180804t151509z
categoryutopian-io
json_metadata"{"app": "beem/0.19.42"}"
created2018-08-04 15:15:09
last_update2018-08-04 15:15:09
depth1
children0
last_payout2018-08-11 15:15:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length308
author_reputation152,955,367,999,756
root_title"Integrate Steemconnect V2 User Authorisation Into Any WordPress Website"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id67,100,616
net_rshares0