getting Error: invalid_client in instamojo - php

I am integrating instamojo payment-gateway in ionic at the server side i putted below code for access token
<?php
class Instamojo
{
private $client_id;
private $client_secret;
private $url = "https://api.instamojo.com/oauth2/token/";
private $env = "production";
public function __construct($client_id, $client_secret)
{
$this->client_id = $client_id;
$this->client_secret = $client_secret;
}
public function getToken() {
if (substr( $this->client_id, 0, 5 ) === "test_") {
$this->url = "https://test.instamojo.com/oauth2/token/";
$this->env = "test";
}
$curl = curl_init($this->url);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, rawurldecode(http_build_query(array(
'client_id' => $this->client_id,
'client_secret' => $this->client_secret,
'grant_type' => 'client_credentials'
))));
$json = json_decode(curl_exec($curl));
if(curl_error($curl))
{
echo 'error:' . curl_error($curl);
}
if (isset($json->error)) {
return "Error: " . $json->error;
throw new \Exception("Error: " . $json->error);
}
$this->token = $json;
return $this->env . $json->access_token;
}
}
$instamojo = new Instamojo("Client ID", "Client Secret");
echo $instamojo->getToken();
?>
when i run this code in url getting error 'Error: invalid_client'.how to get Client ID and Client Secret from instamojo account. In instamojo i am getting only API Key, Auth Token and Salt in api and plugin section.
Solved.
1. Go to App & Plugin Section under instamojo account.
2. Click on Generate Credentials Button
3. Choose Ionic-SDK under Platform/Framework then Click on Generate
4. Credentials Button. Got Client ID and Client Secret.

Related

Soundcloud API (PHP) returns "invalid grant"

We are using the code below to try to upload tracks from our WordPress site to SoundCloud through PHP. MP3 tracks are already on our server before running this script.
function upload_soundcloud()
{
//App credentials. Create one at http://soundcloud.com/you/apps
define('API_URL', 'https://api.soundcloud.com');
define('CLIENT_ID', '$client_id');
define('CLIENT_SECRET', '$client_secret');
//User credentials
define('EMAIL', '$email');
define('PASSWORD', '$password');
//Path to MP3 file to upload
define('FILE', ABSPATH . '/wp-content/uploads/path/to/file.mp3');
class SoundcloudAPI {
private $url;
private $clientID;
private $secret;
private $accessToken;
public function __construct($url, $clientID, $secret) {
$this->url = $url;
$this->clientID = $clientID;
$this->secret = $secret;
}
public function auth($username, $password) {
$url = $this->url . '/oauth2/token';
$data = array(
'client_id' => $this->clientID,
'client_secret' => $this->secret,
'grant_type' => 'password',
'username' => $username,
'password' => $password
);
$result = $this->request($url, $data, 'POST');
$this->accessToken = $result->access_token;
return $result;
}
public function upload($title, $path) {
$url = $this->url . '/tracks';
$data = array(
'oauth_token' => $this->accessToken,
'track[title]' => $title,
'track[asset_data]' => new CurlFile(realpath($path), 'audio/mpeg'),
);
$result = $this->request($url, $data, 'POST');
return $result;
}
private function request($url, $data, $method) {
$curl = curl_init();
if ($method === 'POST') {
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
} else {
$url .= '?' . http_build_query($data);
}
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$result = json_decode(curl_exec($curl));
curl_close($curl);
return $result;
}
}
$soundCloud = new SoundcloudAPI(API_URL, CLIENT_ID, CLIENT_SECRET);
$resultAuth = $soundCloud->auth(EMAIL, PASSWORD);
$resultUpload = $soundCloud->upload('Test', FILE);
echo '<pre>';
print_r($resultAuth);
print_r($resultUpload);
echo '</pre>';
}
This is what we are getting as a response:
stdClass Object
(
[error] => invalid_grant
)
Does anyone know why this might be happening? (the strangest part is that it was actually working 2 days ago, but then just stopped working and I feel like I am going crazy).
Try and save the access token and refresh token between requests (for example, in a local file or database) and reusing it. The rate-limit only seems to be on the /oauth2/token endpoint when using a username and password.
Once your access token has expired, you can use the refresh token to get a new one by making a request to /oauth2/token with:
'grant_type': 'refresh_token',
'client_id': <your client id>,
'client_secret': <your client secret>,
'refresh_token': <previous refresh token>

cURL PUT/PATCH request with Discord API resulting in error 400 (BAD REQUEST)

I am using php, oAuth2 (from Discord) and cURL to connect to the Discord API, where after the user authorizes the connection, he will automatically enter the server (guild) with a specific nickname and role, but if the user is already on the server, just changes the nickname and adds the role automatically.
I've had success with Auth2, so I'm looking at it. He returns everything I wanted, using identy, guilds.join and email scopes. However, in the process of adding the member to the server or editing the member, it returns error 400 (BAD REQUEST). And I really don't have a clue what it is, so what I'm seeing seems to be all right.
The strange thing is that yesterday, it was working only in the anonymous browser tab, but today, it even worked in my normal browser, but for other users, it does not work.
To tell you the truth, I've already got error 400 and 403, it's really very confusing.
My complete code:
class Discord extends CodonModule {
private static $OAUTH2_CLIENT_ID = 'CLIENT_ID';
private static $OAUTH2_CLIENT_SECRET = 'CLIENT_SECRET';
private static $BOT_TOKEN = 'CLIENT_TOKEN';
private static $guildID = 453922275248265175;
private static $roleID = 45129328442467690261;
public static $authorizeURL = 'https://discordapp.com/api/oauth2/authorize';
public static $tokenURL = 'https://discordapp.com/api/oauth2/token';
public static $apiURLBase = 'https://discordapp.com/api/users/#me';
public function login() {
$params = array(
'client_id' => Discord::$OAUTH2_CLIENT_ID,
'redirect_uri' => 'LINK/request',
'response_type' => 'code',
'scope' => 'identify guilds.join email'
);
// Redirect the user to Discord's authorization page
header('Location: https://discordapp.com/api/oauth2/authorize' . '?' . http_build_query($params));
die();
}
public function request() {
if($this->get('code')) {
// Exchange the auth code for a token
$token = $this->apiRequest(Discord::$tokenURL, array(
"grant_type" => "authorization_code",
'client_id' => Discord::$OAUTH2_CLIENT_ID,
'client_secret' => Discord::$OAUTH2_CLIENT_SECRET,
'redirect_uri' => 'LINK/request',
'code' => $this->get('code')
));
$logout_token = $token->access_token;
$_SESSION['access_token'] = $token->access_token;
header('Location: ' . $_SERVER['PHP_SELF']);
}
if($this->session('access_token')) {
$user = $this->apiRequest(Discord::$apiURLBase);
$userID = intval($user->id);
$userTAG = $user->username.'#'.$user->discriminator;
$newName = 'Teste';
$params = '{"access_token": "'.$_SESSION['access_token'].'", "nick": "'.$newName.'", "roles": ['.Discord::$roleID.']}';
$code = $this->membersRequest($userID, 'PUT', $params);
// The pilot is not on the guild
if($code == 201) {
$this->show('discord/discord_success.php');
return true;
} elseif($code == 204) {
// The pilot is already on the server
$params2 = '{"nick": "'.$newName.'", "roles": ['.Discord::$roleID.']}';
$http = $this->membersRequest($userID, 'PATCH', $params2);
if($http == 204) {
$this->show('discord/discord_success.php');
return true;
} else {
$this->show('discord/discord_error.php');
return false;
}
} else {
$this->show('discord/discord_error.php');
return false;
}
} else {
$this->index();
}
}
function apiRequest($url, $post=FALSE, $headers=array()) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
if($post)
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$headers[] = 'Accept: application/json';
if($this->session('access_token'))
$headers[] = 'Authorization: Bearer ' . $this->session('access_token');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
return json_decode($response);
}
function membersRequest($userID, $post, $params) {
$membersURL = 'https://discordapp.com/api/guilds/'.Discord::$guildID.'/members/';
$url = $membersURL.$userID;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $post);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bot ' . Discord::$BOT_TOKEN,
'Content-Type: application/json'
));
curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return $http;
}
function get($key, $default=NULL) {
return array_key_exists($key, $_GET) ? $_GET[$key] : $default;
}
function session($key, $default=NULL) {
return array_key_exists($key, $_SESSION) ? $_SESSION[$key] : $default;
}
}
Any help would be much appreciated. Thank you so much.

How can I get an Authentication Token for Microsoft Translator API?

I want to get an Authentication Token for the Microsoft Translator API. This is my code:
<?php
//1. initialize cURL
$ch = curl_init();
//2. set options
//Set to POST request
curl_setopt($ch, CURLOPT_POST,1);
// URL to send the request to
curl_setopt($ch, CURLOPT_URL, 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken');
//return instead of outputting directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//whether to include header in the output. here set to false
curl_setopt($ch, CURLOPT_HEADER, 0);
//pass my subscription key
curl_setopt($ch, CURLOPT_POSTFIELDS,array(Subscription-Key => '<my-key>'));
//CURLOPT_SSL_VERIFYPEER- Set to false to stop verifying certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//3. Execute the request and fetch the response. check for errors
$output = curl_exec($ch);
if ($output === FALSE) {
echo "cURL Error" . curl_error($ch);
}
//4. close and free up the curl handle
curl_close($ch);
//5. display raw output
print_r($output);
?>
it gives me the following error:
{ "statusCode": 401, "message": "Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API." }
which could mean that the key is invalid according to the website below, but I ensured the key is valid on the same website.
http://docs.microsofttranslator.com/oauth-token.html
I did find some examples online on how to get the Authenticationtoken, but they are outdated.
How can I get the AuthenticationToken/achieve that microsoft recognises my key?
You're passing the subscription-key wrong -
The subscription key should passed in the header (Ocp-Apim-Subscription-Key) or as a querystring parameter in the URL ?Subscription-Key=
And you should use Key1 or Key2 generated by the Azure cognitive service dashboard.
FYI - M$ has made a token generator available for testing purposes, this should give you a clue which keys are used for which purpose:
http://docs.microsofttranslator.com/oauth-token.html
Here's a working PHP script which translates a string from EN to FR (it's based on an outdated WP plugin called Wp-Slug-Translate by BoLiQuan which I've modified for this purpose):
<?php
define("CLIENTID",'<client-name>'); // client name/id
define("CLIENTSECRET",'<client-key>'); // Put key1 or key 2 here
define("SOURCE","en");
define("TARGET","fr");
class WstHttpRequest
{
function curlRequest($url, $header = array(), $postData = ''){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if(!empty($header)){
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
if(!empty($postData)){
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($postData) ? http_build_query($postData) : $postData);
}
$curlResponse = curl_exec($ch);
curl_close($ch);
return $curlResponse;
}
}
class WstMicrosoftTranslator extends WstHttpRequest
{
private $_clientID = CLIENTID;
private $_clientSecret = CLIENTSECRET;
private $_fromLanguage = SOURCE;
private $_toLanguage = TARGET;
private $_grantType = "client_credentials";
private $_scopeUrl = "http://api.microsofttranslator.com";
private $_authUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
// added subscription-key
private function _getTokens(){
try{
$header = array('Ocp-Apim-Subscription-Key: '.$this->_clientSecret);
$postData = array(
'grant_type' => $this->_grantType,
'scope' => $this->_scopeUrl,
'client_id' => $this->_clientID,
'client_secret' => $this->_clientSecret
);
$response = $this->curlRequest($this->_authUrl, $header, $postData);
if (!empty($response))
return $response;
}
catch(Exception $e){
echo "Exception-" . $e->getMessage();
}
}
function translate($inputStr){
$params = "text=" . rawurlencode($inputStr) . "&from=" . $this->_fromLanguage . "&to=" . $this->_toLanguage;
$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?$params";
$accessToken = $this->_getTokens();
$authHeader = "Authorization: Bearer " . $accessToken;
$header = array($authHeader, "Content-Type: text/xml");
$curlResponse = $this->curlRequest($translateUrl, $header);
$xmlObj = simplexml_load_string($curlResponse);
$translatedStr = '';
foreach((array)$xmlObj[0] as $val){
$translatedStr = $val;
}
return $translatedStr;
}
}
function bing_translator($string) {
$wst_microsoft= new WstMicrosoftTranslator();
return $wst_microsoft->translate($string);
}
echo bing_translator("How about translating this?");
?>
Add your key also in the URL.
curl_setopt($ch, CURLOPT_URL, 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken?Subscription-Key={your key}');
But leave it also in the CURLOPT_POSTFIELDS.

How to replace tokens on email campain using REST API in PHP ?

I have an email campaign on Marketo to send emails using PHP. on my email template I have a token like, {{my.emailBody:default=Body}} I would like to replace the the token with my custom email content from my PHP code,
This is my code,
$sample = new SendSampleEmail();
$sample->id = 11111;
$sample->emailAddress = "myemail#example.com";
print_r($sample->postData());
class SendSampleEmail{
private $host = "https://AAA-AAA-121.mktorest.com";
private $clientId = "dxxxxxxxxxxxxxxxxxxxxx1";
private $clientSecret = "Sxxxxxxxxxxxxxxxxxxxxxxxxxxxxe";
public $id; //id of to delete
public $emailAddress;//email address to send to
public $textOnly;//boolean option to send text only version
public $leadId;// id of lead to impersonate
public function postData(){
$url = $this->host . "/rest/asset/v1/email/" . $this->id . "/sendSample.json?access_token=" . $this->getToken();
$requestBody = "&emailAddress=" . $this->emailAddress;
if (isset($this->textOnly)){
$requestBody .= "&textOnly=" . $this->textOnly;
}
if (isset($this->leadId)){
$requestBody .= "&leadId=" . $this->leadId;
}
//print_r($requestBody);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('accept: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
curl_getinfo($ch);
$response = curl_exec($ch);
return $response;
}
private function getToken(){
$ch = curl_init($this->host . "/identity/oauth/token?grant_type=client_credentials&client_id=" . $this->clientId . "&client_secret=" . $this->clientSecret);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('accept: application/json',));
$response = json_decode(curl_exec($ch));
curl_close($ch);
$token = $response->access_token;
return $token;
}
}
Using this code I can successfully trigger the emails, but how can I replace the token value {{my.emailBody:default=Body}} ?
I have the same problem which I tried to used Assets Tokens from the REST API: http://developers.marketo.com/rest-api/assets/tokens/
to modify token's values, but it is the only endpoint I cannot make it work. Please let me know if you could make it work.
However, I used the SOAP API to solve for this issue:
You create a Batch Campaign from Marketo inside a Marketo Program that contains the Token you want to modify and the email you want to send using that token.
The SOAP API will schedule the campaign to run (you can set the current time for immediate run), and you can set the value for the tokens:
public function schedule_campaign($program_name,$campaign_name,$token_name,$token_value)
{
$params = new stdClass();
$params->programName = $program_name;
$params->campaignName = $campaign_name;
$dtzObj = new DateTimeZone("America/New_York");
$dtObj = new DateTime('now', $dtzObj);
$params->campaignRunAt = $dtObj->format(DATE_W3C);
$token = new stdClass();
$token->name = "{{my.".$token_name."}}";
$token->value = $token_value;
$params->programTokenList = array("attrib" => $token);
$params = array("paramsScheduleCampaign" => $params);
$soapClient = new SoapClient(MARKETO_SOAP_ENDPOINT ."?WSDL", self::$auth_options);
try
{
$response = $soapClient->__soapCall('scheduleCampaign', $params, self::$auth_options, self::$auth_header);
return true;
}
catch(Exception $ex) {
return false;
}
}
UPDATE:
I've found the way to update/replace tokens using REST API:
public function create_token($folder_id,$name,$content,$folder_type = 'Program')
{
$folder_id = intval($folder_id);
$endpoint = 'rest/asset/v1/folder/'.$folder_id.'/tokens';
$url = $this->url . $endpoint . ".json?access_token=" . self::$token."&folderType=".$folder_type."&name=".$name."&type=". urlencode('rich text')."&value=".urlencode($content);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POST, 1);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response);
}
Token replacement only works with the Request Campaign and Schedule Campaign APIs, you can't replace my tokens with the send sample email API.

"An access token is required to request this resource." while posting message to FB page using PHP

I'm trying to create one PHP application which ll post message to FB page directly. But facing some issues while posting message. I got following error:-
{
"error": {
"message": "An access token is required to request this resource.",
"type": "OAuthException",
"code": 104
}
}
Following is my code:-
<?php
class Facebook
{
private $page_id = 'Page ID';
private $page_access_token = 'access-code';
private $post_url = '';
public function Facebook()
{
$this->post_url = 'https://graph.facebook.com/'.$this->page_id.'/feed';
}
public function message($data)
{
$data['access_token'] = $this->page_access_token;
$ch = curl_init();
echo "Link:- ".$this->post_url;
curl_setopt($ch, CURLOPT_URL, $this->post_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($ch);
curl_close($ch);
return $return;
}
}
$facebook = new Facebook();
$facebook->message(array( 'message' => 'Best Service'));
?>
I tried alot to solve this error. I checked access token n page ID also both are correct but still getting this error.
Please guide me to solve this error....
Thanks in advance......

Categories