DocuSign API Returns Un Authorized Client - php

I am getting 400 bad request with DocuSign demo account while accessing access token. I am using these values while making call.
$url = "https://account-d.docusign.com/oauth/token";
$integrator_and_secret_key = "Basic " . base64_encode("integration key:secret key");
$headers = [
"Authorization" => $integrator_and_secret_key,
"Content-Type" => "application/x-www-form-urlencoded",
];
$postData = [
"grant_type" => "authorization_code",
"code" => $_GET['code'],
];
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, "grant_type=authorization_code&code=authcode");
curl_setopt($curl, CURLOPT_HTTPHEADER,$headers
);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_VERBOSE, true);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
echo "error calling webservice, status is:" . $status . "\nerror text is --> ";
print_r($json_response); echo "\n";
exit(-1);
}
echo "<pre>"; print_r($json_response); exit;
$response = json_decode($json_response, true);
// if(isset($response["envelopeId"])){
// echo json_encode(array('output'=>'success'));
// }
// else{
// echo json_encode(array('status'=>False,'output'=>'Fail'));exit;
// }
exit;
There was an error calling "web service" after I called above, status: 400 error text -> error "error": "invalid_grant", "error_description": "unauthorized_client"} "

It looks like you're attempting to use the oauth authorization code grant flow.
The code that your q shows is the second major step where your app exchanges the authorization code it received from DocuSign for an access token that will be used to call the API.
Your code appears to be using the static string authcode as the authorization code:
curl_setopt($curl, CURLOPT_POSTFIELDS,
"grant_type=authorization_code&code=authcode");
This is a bug. The code body parameter must be set to the value of the authorization code that was previously received from DocuSign.
Eg
curl_setopt($curl, CURLOPT_POSTFIELDS,
"grant_type=authorization_code&code=$authcode");
Recommendation
Instead of hand-coding the authorization code grant, it is better to use a library. For PHP, the open source league/oauth2-client can be used. Docs
The DocuSign code example shows how to use it. See the Auth directory and its callers.

Related

OpenAI API error: "You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth"

I am creating a PHP script to access Open Ai's API, to ask a query and get a response.
I am getting the following error:
You didn't provide an API key. You need to provide your API key in an
Authorization header using Bearer auth (i.e. Authorization: Bearer
YOUR_KEY)
...but I thought I was providing the API key in the first variable?
Here is my code:
$api_key = "sk-U3B.........7MiL";
$query = "How are you?";
$url = "https://api.openai.com/v1/engines/davinci/jobs";
// Set up the API request headers
$headers = array(
"Content-Type: application/json",
"Authorization: Bearer " . $api_key
);
// Set up the API request body
$data = array(
"prompt" => $query,
"max_tokens" => 100,
"temperature" => 0.5
);
// Use WordPress's built-in HTTP API to send the API request
$response = wp_remote_post( $url, array(
'headers' => $headers,
'body' => json_encode( $data )
) );
// Check if the API request was successful
if ( is_wp_error( $response ) ) {
// If the API request failed, display an error message
echo "Error communicating with OpenAI API: " . $response->get_error_message();
} else {
// If the API request was successful, extract the response text
$response_body = json_decode( $response['body'] );
//$response_text = $response_body->choices[0]->text;
var_dump($response_body);
// Display the response text on the web page
echo $response_body;
All Engines endpoints are deprecated.
This is the correct Completions endpoint:
https://api.openai.com/v1/completions
Working example
If you run php test.php in CMD, the OpenAI API will return the following completion:
string(23) "
This is indeed a test"
test.php
<?php
$ch = curl_init();
$url = 'https://api.openai.com/v1/completions';
$api_key = '<OPENAI_API_KEY>';
$post_fields = '{
"model": "text-davinci-003",
"prompt": "Say this is a test",
"max_tokens": 7,
"temperature": 0
}';
$header = [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
}
curl_close($ch);
$response = json_decode($result);
var_dump($response->choices[0]->text);
?>

How to post JSON data and a request token(in the header) in cURL php

I want to send the login credentials and a pin number as a JSON data and the request token as my http header.
initially it's like this,
{
"Username":"admin",
"Password":"root123",
"PinCode” : "hello321"
}
and I need to post my Request Header token as well.
and if the request is ok, I should get JSON response as follow,
{
"Title": "Mr.",
"Name": "Pushkov",
"Age": "18"
}
I'm trying to do it in cURL PHP. Below is my controller code.
I tried to save my request token to a variable and pass it in header and post username, password and pinnumber as JSON data. if the login success than user info should be displayed. but I'm struggling to move ahead from here. How can I achieve that?
public function send_data() {
$url='http://samplesite.azurewebsites.net/api/member/loginmember';
$ch = curl_init('http://localhost/main');
$data = array("Username" =>$this->input->post('un'), "Password" =>$this->input->post('pw'), "PinCode" =>$this->input->post('PinCode'));
$data_string = json_encode($data);
//echo $data_string;
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
//var_dump(json_decode($result, true));
$data2=json_decode($result, true);
$ref_id = ( ( is_array( $data2["UserCode"] ) ? implode(", ", $data2["PinCode"]) : $data2["RequestToken"] ) ); // array to string
$acc_t = $data2["RequestToken"];
$uun = $data2["UserCode"];
//echo $acc_t;
// Closing
curl_close($ch);
//print $result ;
}
In your code above, you set a URL to curl_init() and you also passed another one in CURLOPT_URL option. You can't do that in one cURL request.
If you are using OAuth 2.0 you can set the access token to CURLOPT_XOAUTH2_BEARER option.
More information, please refer to PHP manual on cURL Functions.

Google identity toolkit: JWT verification fails with status 500, "message": null

According to the implementation guide and common sense, I'd like to verify the JWT token issued to an user who has logged in to my site through the Google Identity Toolkit, to prevent forgery and.. just in case.
A POST request through cURL (code below) to https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo containing the idToken (string), localId (list) and email (list) should suffice. My application uses as a local id the tokenId issued by the IDSP.
However, this is what I get:
Error: call to URL https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo?key=MyAPIKey failed with status 500, response { "error": { "code": 500, "message": null } } , curl_error , curl_errno 0
And frankly, I'm at utter loss: my Google-fu only turned up logging out and back in, but unsurprisingly it hasn't solved the issue.
Of further concern is the necessity of fetching the user display name and image, through the same relyingparty.
Code
function verifytoken($data){
$url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo?key=MyAPIKey";
var_dump($data);
$content = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
var_dump($response);
}
$tok=array('idToken'=>$gitkitUser->getUserId(),'localId'=>array($gitkitUser->getUserId()),'email'=>array($gitkitUser->getEmail()));
verifytoken($tok);
To verify the Google Identity Toolkit JWT token, you do not need to make any HTTP request. It is recommended to use one of the Google Identity Toolkit libraries (Java/Python/Php/Ruby/Go/Nodejs) to do that locally. The token already includes the email/name/photo_url of the user.

gcm push notification: first success, then not registered in IOS

After all passages for receive the notification with google cloud messaging in IOS but i have this problem:
i send the post in php for the notification with server key and device's token, at first time the response is "success" but not receive nothing on device, at the second time, and subsequent times, the response is "notRegistered". I repeat all passages: create new key in keychain, load in provisioning profile, download the .cer, install in keychain, export .p12 and insert the certificates on google platform for "GoogleService-Info.plist" and reload the device's regId at php, but the response is always this. Help me please.
This is my php :
$apiKey = "server key";
$regId = 'registration token';
$url = 'https://gcm-http.googleapis.com/gcm/send';
$post = '{"to" : "' . $regId . '", "content_available" : true, "priority" : "high", "notification": {"title" : "test", "body" : "test"}}';
$headers = array(
"Authorization:key=$apiKey",
'Content-Type:application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
if ( curl_errno( $ch ) )
{
echo 'GCM error: ' . curl_error( $ch );
}
curl_close( $ch );
echo $result;
Op's own answer, removed from the edited question:
The problem was the old account without the new provisioning profile, go to : XCode Accounts -> Apple IDs and view details -> Download All. For be sure go to : Targets -> project name -> Build Settings -> search "Provisioning Profile" -> change automatic and select your provisioning profile in use for certificates. The mystery is the xcode's reason don't warning me don't find the correct Provisioning Profile (different bundle id).
My five cents
In case you are having "notRegistered" error only when app is in production that was my mistake: I missed the that in the registration options provided in GCM:
[[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:_gcmSenderID
scope:kGGLInstanceIDScopeGCM
options:_registrationOptions
handler:self.registrationHandler];
There is an option kGGLInstanceIDAPNSServerTypeSandboxOption which should be set to NO in case of production
Hope it helps!
Some week ago, we also got NotRegistered error on second message send attempt. But For my experience, problem is not on ios side. The problem is on sent message parameters.
Please try to send all required and optional parameters.
Maybe you want to give a try to PHP script on this Q&A
Tip: Sending parameter "content_available as true, priority as high and notification as data" may help.
Below Example Json received with success again and again by ios devices.
"Content-Type" is "application/json"
{
"registration_ids":[
"<reg_id1>",
"<reg_id2>",
],
"priority":"high",
"content_available":true,
"time_to_live":2419200,
"data":{
"message":"Test 15:46:49",
"title":""
},
"notification":{
"title":"",
"body":"Test 15:46:49",
"sound":"default",
"badge":"1"
}
}
Edit 2:
Give a try that;
$apiKey = "server key";
$regId = 'registration token';
$url = 'https://gcm-http.googleapis.com/gcm/send';
$post = '{"to" : "' . $regId . '","priority":"high","content_available":true,"time_to_live":2419200,"data":{"message":"GCM Notifier:Message Success","title":"GCM Notifier:Title Success"},"notification":{"title":"GCM Notifier:Title Success","body":"GCM Notifier:Message Success","sound":"default","badge":"1"}}';
$headers = array(
"Authorization:key=$apiKey",
'Content-Type:application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
if ( curl_errno( $ch ) )
{
echo 'GCM error: ' . curl_error( $ch );
}
curl_close( $ch );
echo $result;

How to send message to youtube user using youtube API?

I am developing a script to send a message to a YouTube user. Actually, I have got the YouTube data feeds with the information - YouTube video id, author name, details etc.., for that corresponding author. I have to send a message using the YouTube api. Is this possible?
I have already written Oauth login and YouTube API feed to get video and user information for that corresponding video. I referred to this documentation in the YouTube API - https://developers.google.com/youtube/2.0/developers_guide_protocol_messages#Sending_a_message for send message, but there are no options for this. There are only options to send message as comments instead of new mail to the inbox of the corresponding video author.
So please update me if you know about that. I have pasted my script below.
$developer_key='###########################';
$client_id= '#################';
$client_secret='#################';
// error checking; user might have denied access
if (isset($_GET['error'])) {
if ($_GET['error'] == 'access_denied') {
echo('You have denied access. Click here to retry…');
} else {
echo("An error has occurred: ". $_GET['error']);
}
exit;
}
// Step 1: redirect to google account login if necessary
if(!isset($_GET['code']) || $_GET['code'] === '') {
Header('Location: https://accounts.google.com/o/oauth2/auth?client_id='. $client_id .
'&redirect_uri=http%3A%2F%2Flocalhost%2Ftest%2Foauth_1.php' .
'&scope=https://gdata.youtube.com&response_type=code&access_type=offline',
true, 307);
exit;
}
$authorization_code= $_GET['code'];
// Step 2: use authorization code to get access token
$url = "https://accounts.google.com/o/oauth2/token";
$message_post= 'code='. $authorization_code .
'&client_id='. $client_id .
'&client_secret='. $client_secret .
'&redirect_uri=http://localhost/test/oauth_1.php' .
'&grant_type=authorization_code';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message_post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if ($cur_error= curl_error($ch)) {
echo($cur_error);
curl_close($ch);
exit;
}
curl_close($ch);
$jsonArray= json_decode($result, true);
if ($jsonArray === null) {
echo("Could not decode JSON.");
exit;
}
if (isset($jsonArray['error'])) {
echo("An error has occurred: ". $jsonArray['error']);
exit;
}
if (!isset($jsonArray['access_token'])) {
echo("Access token not found.");
exit;
}
//The user's authentication token
$access_token= $jsonArray['access_token'];
$title ='krishna'; //The title of the caption track
$lang = 'en'; //The languageof the caption track
//$transcript = $_REQUEST['transcript']; //The caption file data
$ur='https://gdata.youtube.com/feeds/api/users/recepient_username/inbox';
$headers = array(
'Host: gdata.youtube.com',
'Content-Type: application/atom+xml utf-8',
'Content-Language: ' . $lang,
'Slug: ' . rawurlencode($title),
'Authorization: AuthSub token=' . $access_token,
'GData-Version: 2',
'X-GData-Key: key=' . $developer_key
);
$xml = '&xml=<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:yt="http://gdata.youtube.com/schemas/2007">
<id>cSVSeHFKBjU</id>
<summary>sending a message from the api</summary>
</entry>';
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_HEADER, TRUE );
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($xml) );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1 );
$tt = curl_getinfo($ch);
print_r($tt);
$result = curl_exec($ch);
print_r($result);
// close cURL resource, and free up system resources
curl_close($ch);
echo "DONE! Token:" . $access_token . "<br />\n";
var_dump($result);
SO please check and update me if there any options to send mail to the video user instead of comments.
The YouTube v2.0 API does support sending new messages to a user's inbox, but the message must contain both a video and a comment about that video. You cannot send a text-only message.
Documentation, which includes a use case explaining how YouTube's messaging support is intended to be used, can be found here.

Categories