PHP post failed cloudflare api - php

i'm trying to update my DNS domain record through cloudflare api using PHP Post, but the cloudflare api send response that POST method is not allowed for the api_token authentication scheme, i already tried the the api using postman and it works, but somehow in PHP the api does not work, is PHP does not support POST using token ?, some variable is stored inside env.php and i hide it because it sensitive information.
PHP code :
include("../../env.php");
//variable input by POST
$domain = $_POST['domain'];
$recordID = $_POST['recordID'];
$content = $_POST['content'];
$zoneID = $_POST['zoneID'];
//for update record
$linkRecord = "https://api.cloudflare.com/client/v4/zones/$zoneID/dns_records/$recordID";
$header = array(
"Content-Type: application/json",
"Authorization: Bearer $authToken"
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $linkRecord);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
$bodyArray = array("type"=>"A","name"=>$domain,"content"=>$content,"proxied"=>true);
$body = json_encode($bodyArray);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
$resp = curl_exec($curl);
print_r($resp);
linkRecord Variable Value:
https://api.cloudflare.com/client/v4/zones/{{my_secret_zone_id}}/dns_records/{{id_of_the_record}}
Cloudflare response of POST :
{
"success": false,
"errors": [
{
"code": 10000,
"message": "POST method not allowed for the api_token authentication scheme"
}
]
}

Related

DocuSign API Returns Un Authorized Client

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.

Displaying cURL JSON response with Dingo API (Laravel)

I'm sending a requests via cURL to an external webservice and I'm receiving a response in JSON format. Something like this:
public function store(Request $request)
{
$loggedInUser = app('Dingo\Api\Auth\Auth')->user();
if (!$loggedInUser instanceof User) {
$this->response->errorUnauthorized();
}
$data = $request->all();
$url = env('WEBSERVICE_URL');
$payload = json_encode(['n' => $data['n']]);
$auth = 'Authorization: ' . env('API_KEY');
$headers = [
'Content-Type:application/json',
$auth
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
The problem is that the response of function is like this
{
"code": 200,
"status": "success",
"data": "{\"message\":\"n saved successfully!\"}"
}
And not like this (the json I received from the webservice)
{"message": "n saved successfully!"}
I'm not really an expert with Dingo API but I can imagine that this probably has to do with some kind of default response format Dingo applies to the returned values in the functions.
Anyways, in this case I would like it to return the second response above mentioned. Is there any way to disable the default response format Dingo applies in particular cases? Or do you think this is caused by something else?

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.

Messenger bot not working

I am trying to set up a very simple bot. I generated an access token, created a simple index.php file on my web server (SSL certified), set up a webhook that points to my index.php file, subscribed my webhook to my page events (everything on developers.facebook.com), messaged my bot and got no answer. What might be the problem?
(I have checked everything: both tokens, I am admin etc.)
Here is my code:
<?php
$access_token = "i-filled-this-out";
$verify_token = "i-also-filled-this-out";
$hub_verify_token = null;
if(isset($_REQUEST['hub_challenge'])) {
$challenge = $_REQUEST['hub_challenge'];
$hub_verify_token = $_REQUEST['hub_verify_token'];
}
if ($hub_verify_token === $verify_token) {
echo $challenge;
}
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
$message_to_reply = '';
$message_to_reply = 'Huh! what do you mean?';
//API Url
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$access_token;
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"text":"'.$message_to_reply.'"
}
}';
//Encode the array into JSON.
$jsonDataEncoded = $jsonData;
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
//Execute the request
if(!empty($input['entry'][0]['messaging'][0]['message'])){
$result = curl_exec($ch);
}
Make sure your webhook is returning a HTTP 200 response to the POST requests sent by facebook.
What web server are you running? Check the logs to see if your webhook is receiving POST requests from facebook (and returning a 200).
Best way of testing your webhook is using something like postman to imitate the standard POSTs made by facebook and checking the responses you are serving.

Executing Curl in PHP to do a Stripe subscription

The Stripe API allows for Curl calls to be made. For example, the command:
curl https://api.stripe.com//v1/customers/cus_5ucsCmNxF3jsSY/subscriptions -u sk_test_REDACTED:
returns the subscription of customer cus_5ucsCmNxF3jsSY.
How can I use PHP to call this curl command (I am trying to avoid using the PHP Stripe libraries).
I am trying the following:
<?php
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "https://api.stripe.com//v1/customers/cus_5ucsCmNxF3jsSY/subscriptions -u sk_test_REDACTED:");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
print($output);
// close curl resource to free up system resources
curl_close($ch);
?>
However, it seems that curl does not take the -u parameter of the URL. I get the following error:
{ "error": { "type": "invalid_request_error", "message": "You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/." }
How can I pass the -u sk_test_REDACTED: parameter to my curl call?
I ran into the same issue. I wanted to use PHP's CURL functions instead of using the official stripe API because singletons make me nauseous.
I wrote my own very simple Stripe class which utilizes their API via PHP and CURL.
class Stripe {
public $headers;
public $url = 'https://api.stripe.com/v1/';
public $method = null;
public $fields = array();
function __construct () {
$this->headers = array('Authorization: Bearer '.STRIPE_API_KEY); // STRIPE_API_KEY = your stripe api key
}
function call () {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
switch ($this->method){
case "POST":
curl_setopt($ch, CURLOPT_POST, 1);
if ($this->fields)
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->fields);
break;
case "PUT":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
if ($this->fields)
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->fields);
break;
default:
if ($this->fields)
$this->url = sprintf("%s?%s", $this->url, http_build_query($this->fields));
}
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true); // return php array with api response
}
}
// create customer and use email to identify them in stripe
$s = new Stripe();
$s->url .= 'customers';
$s->method = "POST";
$s->fields['email'] = $_POST['email'];
$customer = $s->call();
// create customer subscription with credit card and plan
$s = new Stripe();
$s->url .= 'customers/'.$customer['id'].'/subscriptions';
$s->method = "POST";
$s->fields['plan'] = $_POST['plan']; // name of the stripe plan i.e. my_stripe_plan
// credit card details
$s->fields['source'] = array(
'object' => 'card',
'exp_month' => $_POST['card_exp_month'],
'exp_year' => $_POST['card_exp_year'],
'number' => $_POST['card_number'],
'cvc' => $_POST['card_cvc']
);
$subscription = $s->call();
You can dump $customer and $subscription via print_r to see the response arrays if you want to manipulate the data further.

Categories