How do I implement sendgrid.env file? - api

I am trying to implement the sendgrid email API.
I have followed all the instructions I can find to try and set up the sendgrid email API but I all I get is this:
Response status: 401 Response Headers - HTTP/1.1 401 Unauthorized
- Server: nginx - Date: Wed, 02 Mar 2022 21:56:45 GMT
- Content-Type: application/json
- Content-Length: 88
- Connection: keep-alive
- Access-Control-Allow-Origin: https://sendgrid.api-docs.io
- Access-Control-Allow-Methods: POST
- Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl
- Access-Control-Max-Age: 600
- X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html
- Strict-Transport-Security: max-age=600; includeSubDomains
I installed the SendGrid helper library, ran the Composer command which created a composer.json file in the root of my project, installed the SendGrid helper library for PHP, along with its dependencies in a new directory named vendor.
I then used the following to create sendgrid.env:
echo "export SENDGRID_API_KEY='SG.XXX....XXXX'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env
The API key works fine when I tested it using curl --request POST and email comes through ok.
But I have tried every combination I can think of to integrate the sendgrid.env e.g. changing the location, removing the single quotes etc. but I just get the same error message every time.
Here is my php script to send the email:
declare(strict_types=1);
require 'vendor/autoload.php';
use \SendGrid\Mail\Mail;
$email = new Mail();
// Replace the email address and name with your verified sender
$email->setFrom(
'paul#xxx.com',
'Paul xxx'
);
$email->setSubject('Sending with Twilio SendGrid is Fun');
// Replace the email address and name with your recipient
$email->addTo(
'paul#yyy.com',
'Paul yyy'
);
$email->addContent(
'text/html',
'<strong>and fast with the PHP helper library.</strong>'
);
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
try {
$response = $sendgrid->send($email);
printf("Response status: %d\n\n", $response->statusCode());
$headers = array_filter($response->headers());
echo "Response Headers\n\n";
foreach ($headers as $header) {
echo '- ' . $header . "\n";
}
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
}
This is the structure of the files:
My domain and email have been verified on Sendgrid.
I have a feeling that there's another step involved to get the API from the sendgrid.env file?
Thanks in advance.

Related

Why does Telegram give me an empty POST request on the webhook?

I followed these steps:
Registered a bot with BotFather.
Send a post request for the webhook (https://api.telegram.org/bot[BOTID]/setWebhook) with the URL being https://example.com/myscript.php
Double check with getWebhookInfo and it showed it is correctly registered.
When I send a message to the bot, the script is being called but with an empty POST payload. In the documentation they say they would send an HTTPS POST request to the specified url, containing a JSON-serialized Update.
Does anyone else has this issue and perhaps know a way to resolve this?
My php script to log:
$file = dirname(__FILE__) . '/telegram-log.txt';
$entry = (object)array();
$entry->date = date("r");
$entry->GET = $_GET;
$entry->POST = $_POST;
$entry->REQUEST = $_REQUEST;
$entry->HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
$entry->REMOTE_ADDR = $_SERVER['REMOTE_ADDR'];
file_put_contents($file, json_encode($entry) . "\n", FILE_APPEND | LOCK_EX);
Response:
{"date":"Thu, 17 Jun 2021 13:42:49 +0200","GET":[],"POST":[],"REQUEST":[],"HTTP_USER_AGENT":null,"REMOTE_ADDR":"91.108.6.133"}
Use $content = file_get_contents("php://input") to receive updates.
Telegram's response is of content-type application/json.
$_POST will only work when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

How to get Header Location value from a Fetch request in browser

From a ReactJS - Redux front app, I try to get the Location Header value of an REST API response.
When I Curl this :
curl -i -X POST -H "Authorization: Bearer MYTOKEN" https://url.company.com/api/v1.0/tasks/
I Have this answer :
HTTP/1.1 202 ACCEPTED
Server: nginx
Date: Fri, 12 Aug 2016 15:55:47 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 0
Connection: keep-alive
Location: https://url.company.com/api/v1.0/tasks/status/idstatus
When I make a Fetch in ReactJS
var url = 'https://url.company.com/api/v1.0/tasks/'
fetch(url, {
method: 'post',
credentials: 'omit',
headers: {
'Authorization': `Bearer ${token}`
}
}
)
I don't have any Headers in the response object :
No header in Fetch request
I tried all the response.headers functions I've found in https://developer.mozilla.org/en-US/docs/Web/API/Headers :
response.headers.get('Location');
But well, as headers is empty, I have empty results.
Do you know why I can't get a proper Header object filled with the headers values ?
Thanks to John, I've found the answer.
I just had to put
Access-Control-Expose-Headers: Location
To my response headers and it worked, so now I can access Location value with :
response.headers.get('Location');
Thx John !
Besides to expose the Location Header in the server.
I just could access the location in the react application with:
response.headers.location;

Graphql post body "Must provide query string."

I use Express-graphql middleware.
I send the following request in the body line:
POST /graphql HTTP/1.1
Host: local:8083
Content-Type: application/graphql
Cache-Control: no-cache
Postman-Token: d71a7ea9-5502-d5fe-2e36-0ae49c635a29
{
testing {
pass(id: 1) {
idn
}
}
}
and have error
{
"errors": [
{
"message": "Must provide query string."
}
]
}
in graphql i can send update in URL.
URL string is too short. i must send update model like
mutation {
update(id: 2, x1: "zazaza", x2: "zazaza", x3: "zazaza" ...(more more fields)...) {
idn
}
}
I think its must be in request body. How can I send 'update' query or that I'm doing wrong?
Post request needs to manage headers info.
Using Http client - Content-Type: application/json
Using Postman client - Content-Type: application/graphql
but request body looks like string
{"query":"mutation{update(id:1,x1:\"zazaz\",x2:\"zazaz\"......){id x1 x2}}"}
If you are using graphql and want to test it using postman or any other Rest client do this.
In postman, select POST method and enter your URL and set Content-Type as application/graphql then pass your query in the body.
Example:
http://localhost:8080/graphql
Mehtod: POST
Content-Type: application/graphql
Body:
query{
FindAllGames{
_id
title
company
price
year
url
}
}
Thats it you will get the response.
Using Postman Version 7.2.2 I had a similar issue. This version of Postman supports Graphql out of the box. Changing the Content-type to application/json fixed it for me.
for me worked like as following:
In the body
In the Headers
Don't forget mark GraphQl [x] on Body settings
And how was quoted before changes the verb to POST.
This generally occurs when your 'express-graphql' doest receive any params. You need to added a json/applicaton parser in your application.
npm install body-parser
eg -
const bodyParser = require('body-parser');
app.use(bodyParser.json()); // application/json
go to the relevant web page and open "inspect" (by write click ->
inspect || Ctrl+Shift+I in chrome)
go to the network tab and copy the cURL command
open the postman ,then import -> raw text
paste the copied command
then,continue ->
Switch content type to JSON.
Like this
Check if you are using correct protocol in your Postman requests.
I used HTTP instead of HTTPS and this caused the same error.
Changes of content-type, raw or json instead of graphql type didn't help.

Client credential grant type is not properly sent with Apache Oltu client library?

I tried to implement an OAuth client using OAuthClientRequest in Apache Oltu. And it seems to be that it is sending client credentials in the message body not in the Basic Auth headers according to the spec. I am not sure, I may have missed some thing in the code.
Code
OAuthClientRequest.tokenLocation("http://localhost:8081/token")
.setGrantType(GrantType.CLIENT_CREDENTIALS)
.setClientId(clientKey)
.setClientSecret(clientSecret)
.buildBodyMessage();
Request
POST /token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Pragma: no-cache
User-Agent: Java/1.6.0_29
Host: 127.0.0.1:8081
Accept: text/html, image/gif, image/jpeg, *; q=.2, /; q=.2
Connection: keep-alive
Content-Length: 127
client_secret=f921854d-f70b-4180-9fdd-3a55032103cc&grant_type=client_credentials&client_id=3f3b4092-7576-4b26-8135-980db7864c2
You might want to change buildBodyMessage() with buildQueryMessage()
The OAuth2 Bearer Token specification defines three methods of sending bearer access tokens:
Authorization Request Header Field
Form-Encoded Body Parameter
URI Query Parameter
The method buildBodyMessage() will create a request with a Form-Encoded Body Parameter. You need to use buildHeaderMessage() instead, which is also the recommended method by the specification.
Recently, I've trying to find a OAuth2 java library to get "client_credential" type of accesstoken. And below is what I have for Apache Oltu, and it seems that it is working.
#Test
public void getAccessTokenViaApacheOltuOAuthClient() {
try{
OAuthClient client = new OAuthClient(new URLConnectionClient());
OAuthClientRequest request =
OAuthClientRequest.tokenLocation(TOKEN_REQUEST_URL)
.setGrantType(GrantType.CLIENT_CREDENTIALS)
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setScope(StringUtils.join(TEST_SCOPES, " ")) //if you have scope
.buildBodyMessage();
String token =
client.accessToken(request, "POST", OAuthJSONAccessTokenResponse.class)
.getAccessToken();
System.out.println(token);
assertTrue( token != null);
} catch (Exception e) {
e.printStackTrace();
}
}

Getting Dropbox - 403 error when logging on using dropboxuploader.php

Hey I'm using dropboxuploader.php to login into dropbox. All was working fine, but when i came into work yesterday i could no longer connect. This is what dropbox is returning to me.
HTTP/1.1 100 Continue
HTTP/1.1 403 Forbidden
Server: nginx/1.2.3
Date: Thu, 04 Oct 2012 08:44:36 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
It seems you tried to do something we can't verify. Did you log into a different Dropbox account in a different window? Try clicking here to go back to the page you came from, or just go home.
Replace the login function with below code and it should work:
protected function login() {
$data = $this->request('https://www.dropbox.com/login');
$str = '<input type="hidden" name="t" value="';
$start = strpos($data,$str);
$val = "";
if($start !== false)
{
$val = substr($data,$start+strlen($str),24);
}
$data = $this->request('https://www.dropbox.com/login', true, array('login_email'=>$this->email, 'login_password'=>$this->password, 't'=>$val));
if (stripos($data, 'location: /home') === false)
throw new Exception('Login unsuccessful.');
$this->loggedIn = true;
}
Just update your dropbox uploader file instead doing your fixes.
https://github.com/jakajancar/DropboxUploader