Github api with PHP - api

Im new in php and im trying to make a script who will create a new repository in github and catch a document that i have in my pc and make a commit in this new repository. This script will be executed in cmd. I search for github api and I have downloaded any folders with several files, i installed some things with a composer, but i cant create a new instance of github in my php.
I don't know anything about this, I spend two days in this and i cant write a function to talk with github. In the site of github developer I dont understand anything, I really need to do this, and im very lost. Im using PhpStorm 6.0.3.
What i cant understand:
1- The api is a folder with a lot of files? Or is a library who is imported in the phpstorm? How i put this in the phpstorm for i can get the methods and create my functions?
2- Where i get the methods for talk with the github api? Where i can see them? In github developer i dont understand nothing.
I see a question similar, but dont help me much.
Please help me
EDIT
I downloaded an api, and i use the composer require, apparently everything is fine, but when i execute some file to test the api, the same error pops up. The program cant find some files that is in the project, in the same folder.
Ex: PHP Fatal error: Interface 'Github\Api\ApiInterface' not found in D:\php-github-api-master\lib\Github\Api\AbstractApi.php on line 15
In anothers files the same error appears, i put "use" referecing the files that im trying to use, but dont work. Ex: use Github\Api\ApiInterface;
EDIT
This code will create a new repository right? When i execute this code I get the error above, Class 'Github\Api\AbstractApi' not found, but the class is in there.
class Repo extends AbstractApi
{
public function create(
$name,
$description = '',
$homepage = '',
$public = true,
$organization = null,
$hasIssues = false,
$hasWiki = false,
$hasDownloads = false,
$teamId = null,
$autoInit = false
) {
$path = null !== $organization ? 'orgs/'.$organization.'/repos' : 'user/repos';
$parameters = array(
'name' => $name,
'description' => $description,
'homepage' => $homepage,
'private' => !$public,
'has_issues' => $hasIssues,
'has_wiki' => $hasWiki,
'has_downloads' => $hasDownloads,
'auto_init' => $autoInit
);
if ($organization && $teamId) {
$parameters['team_id'] = $teamId;
}
return $this->post($path, $parameters);
}
}
Thanks,
Johann.

I finish my script, everything was done correct, sorry for my obviosly questions and thanks for who was answer me. My code:
<?php
include "vendor/autoload.php";
$client = new \Github\Client();
$username = "JohannLucas";
$password = "mypassword";
$method = Github\Client::AUTH_HTTP_PASSWORD;
//authenticate
$client->authenticate($username, $password, $method);
//Apagar Repositório
//$client->api('repo')->remove('JohannLucas', 'teste');
//Criar Repositório
$client->api('repo')->create('olamundo', 'Repositorio criado com o github api', 'http://my-repo-homepage.org', true);
//Commit
$committer = array('name' => 'JohannLucas', 'email' => 'johann.lucas#hotmail.com');
$path = "teste.txt";
$commitMessage = "Commit do teste.txt";
$content = "Olá Mundo!";
$branch = "master";
$repo = "olamundo";
$fileInfo = $client->api('repo')->contents()->create('JohannLucas', 'olamundo', $path, $content, $commitMessage, $branch, $committer);
print_r("Foi!");
Thanks!
Johann

Related

"Attempt to read property \"id\" on null", Create access token error with laravel passport, laravel 9, php 8.2.2

devs,
so I have been struggling with this problem for about 10 hours now, and I can't seem to find a solution online, worst is that I don't even know why it happens.
I am working on a project which uses PHP LARAVEL as the backend and I started writing the API for the flutter frontend to consume then I ran into this error while trying to test the API endpoint for registering and logging in.
The problem is the process fails with this error when I try to generate or create a token for the registered user or logged-in user.
Here a snapshot of my register function
public function store(Request $request)
{
$validated = Validator::make($request->all(),[
"email" => "required|email",
"password" => 'required',
"first_name"=> "required",
"last_name" => "required",
"phone_number" => 'required',
]);
if ($validated->fails()) {
return response()->json(['errors' => "Invalide credentials"], 403);
}
$user = User::create(
// [
// 'first_name' => $request->first_name,
// 'last_name'=> $request->last_name,
// 'email' => $request->email,
// 'password' => bcrypt($request->password),
// 'phone_number' => $request->phone_number,
// ]
$request->toArray()
);
Auth::guard('api')->check($user);
// $newUser = User::find($user->id);
$token = $user->createToken('authToken')->accessToken;
// return $token;
return response(['token' => $token, 'first_name'=>$user->first_name, 'email'=>$user->email ], 200);
}
The login and register functions all look the same at this point.
Error-causing code is :
$token = $user->createToken('authToken')->accessToken;
Please I am open to your suggestions, thanks.
I finally found a solution for this error and I believe it will help anyone out there with a similar problem.
The problem originates from the fact that your application is unable to asign a unique id to your client, remember your website or mobile app is a client to the backend with also(your mobile app or website) might have other users, so laravel passport will need to identify it with a unique id, below are some of the steps i used to fix this error.
First it originates because during the passport installation, i forgot to install
Blockquote
--uuids
If you have a similar error, follow the steps below to fix:
NOTE: You must have laravel passport installed already, if not, them follow the complete installtion guide Here
Step 1:
Install passport uuids
php artisan passport:install --uuids
Your result will look something like
After creating, the uuid for your application, you will have to include it in your .env file as such:
PASSPORT_PERSONAL_ACCESS_CLIENT_ID=986eb40c-0458-4b6e-bead-ea2fc4987033
PASSPORT_PERSONAL_ACCESS_CLIENT_SECRET=VXLdTpqWK9i3CBqFwZgje5fuerQ5Uf2lvwXJqBoP
And there you go, you can now try to do what you couldn't do before.

Laravel site cant be reached for this DotenvEditor

I am uses Dotenveditor to save the env parameters but after redirecting i faced error as
This site can’t be reachedThe connection was reset.
Try:
Checking the connection
Checking the proxy and the firewall
ERR_CONNECTION_RESET
what is mistake in my code? rest part of controller works properly.
if (isset($request->APP_DEBUG)) {
$env_update = DotenvEditor::setKeys(['APP_DEBUG' => 'true']);
} else {
$env_update = DotenvEditor::setKeys(['APP_DEBUG' => 'false']);
}
if (isset($request->COOKIE_CONSENT_ENABLED)) {
$env_update = DotenvEditor::setKeys(['COOKIE_CONSENT_ENABLED' => 'true']);
} else {
$env_update = DotenvEditor::setKeys(['COOKIE_CONSENT_ENABLED' => 'false']);
}
$env_update = DotenvEditor::setKeys([
'APP_NAME' => preg_replace('/\s+/', '', $request->title),
'APP_URL' => preg_replace('/\s+/', '', $request->APP_URL),
]);
$env_update->save();
Try to update your .env file using notepad++ as administrator. I Think it is much easier and user friendly. When you make the necessary changes save the file. Afterwords, I think you must reboot to the Virtual Machine (if you are using one) or restart the service in order the change takes effect to the application.
Talking about Laravel-Dotenv-Editor please try to visit Dotenv editor in order to find more information.
Example of a .env file:

Web push notification example with PHP backend

I am looking for an example for web push notification with JS code and PHP backend. Can anyone share example code or a tutorial?
Here's a basic example that uses web-push-php : https://github.com/Minishlink/web-push-php-example
Main PHP code is:
<?php
require __DIR__ . '/vendor/autoload.php';
use Minishlink\WebPush\WebPush;
$auth = array(
'VAPID' => array(
'subject' => 'https://github.com/Minishlink/web-push-php-example/',
'publicKey' => 'BCmti7ScwxxVAlB7WAyxoOXtV7J8vVCXwEDIFXjKvD-ma-yJx_eHJLdADyyzzTKRGb395bSAtxlh4wuDycO3Ih4',
'privateKey' => 'HJweeF64L35gw5YLECa-K7hwp3LLfcKtpdRNK8C_fPQ', // in the real world, this would be in a secret file
),
);
$webPush = new WebPush($auth);
$res = $webPush->sendNotification(
$subscription['endpoint'],
"Hello!", // payload
$subscription['key'],
$subscription['token'],
true // flush
);
// handle eventual errors here, and remove the subscription from your server if it is expired
Hope this helps :)

Class 'KeenIO\Client\KeenIOClient' not found

I am including Keen in my product (code snippet below)
require INCLUDE_DIR . '/vendor/autoload.php'; // Autoloader for Composer (https://getcomposer.org/)
use KeenIO\Client\KeenIOClient;
class Statistics extends Model {
private $client;
public function __construct( $id = null ){
parent::__construct();
$this->client = KeenIOClient::factory([
'projectId' => KEEN_PROJECT_ID,
'writeKey' => KEEN_WRITE_KEY,
'readKey' => KEEN_READ_KEY
]);
}
...
but I continue to get an "Class 'KeenIO\Client\KeenIOClient' not found" error when the "KeenIOClient::factory" line runs. I was able to successfully install Keen.io through Composer - I feel it's something simple I'm missing - any ideas?
So I can't leave a comment, but I am wondering if there is maybe an issue with the include path? I was able to get this PHP snippet to work:
require 'vendor/autoload.php';
use KeenIO\Client\KeenIOClient;
$client = KeenIOClient::factory([
'projectId' => "53f3a8687d8cb95095000001",
'readKey' => "99a06e48fd7fb1279bc40995160eb0b61a9e0efaab8b651b029f0d895f77c0a804ba089282eff28bf8ad07f337422441d0542b7feaac9fea1e92fc153ee7efc51afad3276bda8d7754a338b349d540bfb402cba0dfdc82498c217054efd8abd0f47a0c0bc963bbdf0dc938c91b17d9f2"
]);
$count = $client->count('bitcoin-prices', [
'impressions' => [
'interval' => 'daily',
'timeframe' => 'this_30_days',
'group_by' => 'keen.timestamp'
]
]);
print_r($count);
That project id and read key are from the keen io open data sets (good to test with).

Error while using REST api in magento

I have set up magento locally in my system using XAMPP
I have created a file in root directory named dm.php with the contents
<?php
/**
* Example of products list retrieve using Customer account via Magento REST API. OAuth authorization is used
*/
$callbackUrl = "http://localhost/dm.php";
$temporaryCredentialsRequestUrl = "http://localhost/mage2/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = 'http://localhost/mage2/oauth/authorize';
$accessTokenRequestUrl = 'http://localhost/mage2/oauth/token';
$apiUrl = 'http://localhost/mage2/api/rest';
$consumerKey = 'enhksf7u33p3snubewb6zcq0z9c63bvv';
$consumerSecret = 'p7e835cdcxofokeep749jgzz4l1e306p';
session_start();
if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {
$_SESSION['state'] = 0;
}
try {
$authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
$oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
$oauthClient->enableDebug();
if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
$_SESSION['secret'] = $requestToken['oauth_token_secret'];
$_SESSION['state'] = 1;
header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
exit;
} else if ($_SESSION['state'] == 1) {
$oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
$accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
$_SESSION['state'] = 2;
$_SESSION['token'] = $accessToken['oauth_token'];
$_SESSION['secret'] = $accessToken['oauth_token_secret'];
header('Location: ' . $callbackUrl);
exit;
} else {
$oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
$resourceUrl = "$apiUrl/products";
$oauthClient->fetch($resourceUrl);
$productsList = json_decode($oauthClient->getLastResponse());
print_r($productsList);
}
} catch (OAuthException $e) {
print_r($e);
}
But this is giving me the following error
Fatal error: Class 'OAuth' not found in D:\Webserver\xampp\htdocs\dm.php on line 19
Can anybody shed some light on this
Thanks
Since oauth is not possible to install in xampp windows i changed the contents of my dm.php file to this.
<?php
$ch = curl_init('http://localhost/mage2/api/rest/customers');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$customers = curl_exec($ch);
echo $customers;
?>
Now i am getting an error like this
{"messages":{"error":[{"code":403,"message":"Access denied"}]}}
What am i doing wrong?
First of all
Go to magento admin panel System->Webservice->RESt Roles->Guest->Resources Access ->SET ALL
Similarly Go to System->Webservice->RESt Attribute->Guest->Resources Access ->SET ALL
Then Hit this url http://****/chanchal/magento/api/rest/products in web Browser and check what error it shows....
According to me it must show product in your website in xml format.
Please let me know..
EDIT:
I configured a localhost just now and got this output refer the Screenshot. Be sure there is product in your magento.
Similarly follow the above steps for admin,customer then create a Ouath consumer from admin panel , Install RESTClient For Mozilla Firefox And follow Here
These for steps are necessary for the setup..the link might help you..
Authentication Endpoints
1./oauth/initiate - this endpoint is used for retrieving the Request Token.
2./oauth/authorize - this endpoint is used for user authorization (Customer).
3./admin/oauth_authorize - this endpoint is used for user authorization (Admin).
4./oauth/token - this endpoint is used for retrieving the Access Token.
Let me know if you have any issues.
Best of luck
A bit of code modifications will easily solve this error 403 forbidden.
What magento engine does is that it uses the default guest user to provide access to the REST api methods. The guest user does not have much powers so it should be better to change this functionality of magento. There are 2 ways of doing this:
1) Quick and dirty fix: in the file /app/code/core/Mage/Api2/Model/Auth.php, change the value of: DEFAULT_USER_TYPE = 'guest' to DEFAULT_USER_TYPE = 'admin'. In the file /app/code/core/Mage/Api2/Model/Auth/Adapter.php, change this line from return (object) array('type' => Mage_Api2_Model_Auth::DEFAULT_USER_TYPE, 'id' => null); to this:
return (object) array('type' => Mage_Api2_Model_Auth::DEFAULT_USER_TYPE, 'id' => '1');
This way the authentication system will not be broken.
2) Proper and long run fix: Override the two functionalities using the magento overriding mechanism to have a better solution in accordance to magento standards. This way the core files will be intact.
We use this link to install oauth for php. Its good and easy to add extension for php.
install oauth php
I hope it helps to all and would solved 'OAuth' not found fatal error.
I had the same issue and was struggling for a week but just try insatlling new version of xammp or wamp with supports ouath.The better solution was ,I installed Ammps 1.9 and in php5.4 I resolved the extension of oauth but still make sure that you select the proper php for extension oauth is supported (php5.4)
For installing Oauth : http://www.magentocommerce.com/api/rest/authentication/oauth_authentication.html
Installing PHP Extension for Oauth :
1. Download php_oauth.dll file and add it under C:\xampp\php\ext\
2. add [PHP_OAUTH] extension=php_oauth.dll in php.ini