I'm trying to execute a PHP script inside my iOS app. It have later to send SMS automatically with the OVH SMS gateway, but for the moment, I only try to connect with my IDs to this service without sending anything.
I get an error 500 (server internal error), and I can't see where is the problem. Here is the tutorial I'm following (in french) : https://www.ovh.com/fr/g1639.envoyer_des_sms_avec_lapi_ovh_en_php
And this is my script (I verified secret keys and it seems to be good, but I don't understand what is the "POST" line commented at the top) :
<?php
/**
* # Instantiate. Visit https://eu.api.ovh.com/createToken/
* to get your credentials
* GET /sms/
* GET /sms/sms-XXXXXX-1/jobs/
* POST /sms/sms-XXXXXX-1/jobs/
*/
require __DIR__ . '/vendor/autoload.php';
use \Ovh\Api;
$applicationKey = "XXX";
$applicationSecret = "XXX";
$consumer_key = "XXX";
$endpoint = 'ovh-eu';
$conn = new Api($applicationKey,
$applicationSecret,
$endpoint,
$consumer_key);
$smsServices = $conn->get('/sms/');
foreach ($smsServices as $smsService) {
print_r($smsService);
echo '{"success":1,"error_message":"All clear"}';
}
?>
And finally my Swift request :
func sendSmsAutoRequest(completionHandler: (responseObject: NSDictionary?, error: NSError?) -> ()) {
let prefs = NSUserDefaults.standardUserDefaults()
let username = prefs.stringForKey("username")!
let messageText = prefs.stringForKey("messagetext")!
let parameters = ["contactsSms": contactsSms, "username": username, "messageText": messageText]
request(.POST, "http://XX.XX.XXX.XXX/dontworry/sendSms.php", parameters: parameters as? [String : AnyObject]).responseJSON { request, response, json, error in
completionHandler(responseObject: json as? NSDictionary, error: error) }
}
Related
I am using twitter account activity api's to send/receive messages. In it i am facing problem in generating webhook. First time it was created successfully. In webhook file i am saving messages in database when each time message sent or received. But when I sent message nothing goes in database. Here is webhook file:
const APP_CONSUMER_SECRET = '**********';
// Example token provided by incoming GET request
if(isset($_REQUEST['crc_token'])) {
$token = $_REQUEST['crc_token'];
/**
* Creates a HMAC SHA-256 hash created from the app TOKEN and
* your app Consumer Secret.
* #param token the token provided by the incoming GET request
* #return string
*/
function get_challenge_response($token) {
$hash = hash_hmac('sha256', $token, APP_CONSUMER_SECRET, true);
$response = array(
'response_token' => 'sha256=' . base64_encode($hash)
);
return json_encode($response);
}
}else{
$feedData = file_get_contents('php://input');
$handleData = fopen('twitterDemo.txt', "w" );
fwrite($handleData,$feedData);
fclose($handleData);
$array = json_decode(file_get_contents('php://input'), true);
if (isset($array['direct_message_events'][0]['type']) && $array['direct_message_events'][0]['type'] == 'message_create' ) {
include_once ('config.php');
include_once ('database-queries.php');
$message = $array['direct_message_events'][0]['message_create']['message_data']['text'];
$sender = $array['direct_message_events'][0]['message_create']['sender_id'];
$from = $array['direct_message_events'][0]['message_create']['target']['recipient_id'];
$message_type = 'incoming';
$message_status = 'unread';
$userId = $sender;
$account_name = 'twitter';
$image_url = '';
if(isset($array['direct_message_events'][0]['message_create']['message_data']['attachment'])){
$image_url = "Not Image";
}
$data = array('to'=>$from, 'from'=>$sender, 'msg'=>$message,'image_url' =>$image_url);
insert($data, $account_name, $message_type, $message_status, $conn);
}
}
I thought there might be webhook problem so i deleted the existing app and create new one and set development environment label for it with new name. But for it when i tried to create webhook it gives me error:
[code] => 214 [message] => Webhook URL does not meet the requirements.
Invalid CRC token or json response format.
I dont know whats happening here now. I am using this api to create webhook url
$url = "https://example.com/twitter/webhook.php";
$result = $connection->post("account_activity/all/env_name/webhooks", ["url" => $url]);
Can anyone please help me this out. Any help will be appreciated.
Thanks!
I ran into the same error message.
The problem seem to be that the
if(isset($_REQUEST['crc_token']))
is not working anymore. Though the token is set. I don't know what is causing the problem but when I let the code just fetch the $_REQUEST['crc_token'] and create and print the hash its working.
But I see your code is not calling the get_challenge_response($token) function.
I think
print get_challenge_response($token)
may help? If the Webhook was deactivated by twitter you have to initiate another CRC check:
https://developer.twitter.com/en/docs/twitter-api/v1/accounts-and-users/subscribe-account-activity/guides/securing-webhooks
Your app can also trigger a CRC when needed by making a PUT request with your webhook id. Triggering a CRC is useful as you develop your webhook application, after deploying new code and restarting your service.
The QuickBooks-V3-PHP-SDK is giving me a hard time.
I'm trying to use it to sync invoice data. I can successfully get authorization using OAuth 2.0 and connect my client PHP web application to QuickBooks Online. However, while I can successfully make a getCompanyInfo call and receive the results, I can't make a getUserInfo call (or most of the other API calls for that matter), as it will complain about the "access token object" not being set yet.
While connecting to QuickBooks and getting authorization, everything seems to work accurately - and the access token object is successfully placed in the PHP Session. But for some reason, it complains when I try to get the UserInfo data, or use any of the other API calls.
Here's the error that I receive:
Fatal error: Uncaught QuickBooksOnline\API\Exception\SdkException: [0]: Can't get OAuth 2 Access Token Object. It is not set yet.
thrown in /compiled/src/Core/OAuth/OAuth2/OAuth2LoginHelper.php on line 129
Here's how I try to get the UserInfo:
$dataService->updateOAuth2Token($accessToken);
$OAuth2LoginHelper = $dataService->getOAuth2LoginHelper();
$result = $OAuth2LoginHelper->getUserInfo();
Again, getting the CompanyInfo works without any problems.
Does anyone have any idea what's going on?
Below I'm including the code from apiCall.php (from the HelloWorld example package, further edited by myself). This file is used to make requests through Ajax after I already connected to and received authorization from QuickBooks Online.
<?php
require_once(__DIR__ . '/vendor/autoload.php');
use QuickBooksOnline\API\Core\ServiceContext;
use QuickBooksOnline\API\DataService\DataService;
use QuickBooksOnline\API\Core\Http\Serialization\XmlObjectSerializer;
use QuickBooksOnline\API\Facades\Invoice;
session_start();
function makeAPICall()
{
// Create SDK instance
$config = include('config.php');
$dataService = DataService::Configure(array(
'auth_mode' => 'oauth2',
'ClientID' => $config['client_id'],
'ClientSecret' => $config['client_secret'],
'RedirectURI' => $config['oauth_redirect_uri'],
'scope' => $config['oauth_scope'],
'baseUrl' => "development"
));
/*
* Retrieve the accessToken value from session variable
*/
$accessToken = $_SESSION['sessionAccessToken'];
$dataService->throwExceptionOnError(true);
/*
* Update the OAuth2Token of the dataService object
*/
$dataService->updateOAuth2Token($accessToken);
//Get the requested data:
$action = filter_input(INPUT_GET, "action", FILTER_SANITIZE_SPECIAL_CHARS);
$method = "get$action";
switch($action){
case "CompanyInfo":
$result = $dataService->$method();
break;
case "UserInfo":
$OAuth2LoginHelper = $dataService->getOAuth2LoginHelper();
$result = $OAuth2LoginHelper->getUserInfo();
break;
case "InvoiceExample":
$allInvoices = $dataService->Query("SELECT * FROM Invoice");
$result = $allInvoices;
break;
}
var_dump($result);
return $result;
}
$result = makeAPICall();
?>
Anyone any idea what I'm doing wrong?
The Intuit (QuickBooks) support team provided the answer to me. In my ApiCall code above, I had to use the following code to make the UserInfo request:
$result = $OAuth2LoginHelper->getUserInfo($accessToken->getAccessToken(), 'development');
Obviously, if this would involve production keys, I would have to replace 'development' with 'production'.
I'm new to PHP development
I'm trying to learn by implementing some real projects for fun.
So I tried to build a bitcoin app where customers can pay in cryptocurrency.
So I start with Coinbase commerce API
I successfully implement the charge page and everything is working well until I reached the point where I have to deal with WEBHOOKS 😔
I'm following this documentation
https://github.com/coinbase/coinbase-commerce-php/blob/master/README.md
And that's the WEBHOOKs code
`<?php
require_once __DIR__ . "/vendor/autoload.php";
use CoinbaseCommerce\Webhook;
/**
* To run this example please read README.md file
* Past your Webhook Secret Key from Settings/Webhook section
* Make sure you don't store your Secret Key in your source code!
*/
$secret = 'SECRET_KEY';
$headerName = 'X-Cc-Webhook-Signature';
$headers = getallheaders();
$signraturHeader = isset($headers[$headerName]) ? $headers[$headerName] : null;
$payload = trim(file_get_contents('php://input'));
try {
$event = Webhook::buildEvent($payload, $signraturHeader, $secret);
http_response_code(200);
echo sprintf('Successully verified event with id %s and type %s.', $event->id, $event->type);
} catch (\Exception $exception) {
http_response_code(400);
echo 'Error occured. ' . $exception->getMessage();
}
`
When I access to the we hooks URL I got this error
Error occured. Invalid payload provided. No JSON object could be decoded
Please 🙏 I want someone to explain to me this error
Thanks in advance.
Seems like you are making a GET (No payload data) request to a url that is expecting a POST (Has payload data) request from the web-hook.
To test API's with POST, PUT, GET requests, you can use tools like PostMan.
You can build JSON payloads manually and test your endpoints.
Try this
$headerName = 'x-cc-webhook-signature';
$signraturHeader = isset($headers[$headerName]) ? $headers[$headerName] : null;
instead of
$headerName = 'X-Cc-Webhook-Signature';
$signraturHeader = isset($headers[$headerName]) ? $headers[$headerName] : null;
I was performing Google Sign in on Android Application for the first time. At the client side, I obtained the access token and sent to the PHP server via POST.
By referring to Google's Documentation, the code I used in backend is as follows:
$id_token = $_POST['id_token'];
$CLIENT_ID = "** MY WEB APPLICATION CLIENT ID **";
$client = new Google_Client(['client_id' => $CLIENT_ID]);
$client->setAuthConfigFile('client_secret.json');
...
$payload = $client->verifyIdToken($id_token);
if ($payload) {
$userid = $payload['sub'];
} else {
echo "Invalid Token";
}
When obtaining user id, the error is : "Cannot use object of type Google_Auth_LoginTicket as array"
I am pretty new to Google sign in. Please point out what all has gone wrong.
Found It. I made some modifications to the code
$token_data = $client->verifyIdToken($id_token)->getAttributes();
$user_id = $token_data['payload']['sub'];
Now the user id is retrieved fine.
Users authorize in my android application. And I am sending users' token and other information to my server. At this server I want to implement some logic for users.
I want to have exactly this flow.
I followed the steps quickstart.php in this link to get users' calendars on server.
But I get following error :
google oauth exception' with message 'could not json decode the token'
For this reason I tried this solution.
But i take same error. So as 3rd option I created the json format myself like in this solution as below.
$access_token = '{
"access_token":'.$access_token.',
"token_type":"Bearer",
"expires_in":3600,
"id_token":'.$id_token.',
"refresh_token":" ",
"created":'. time() .'
}';
as you see I do not know how to exchange refresh token . I searched how to get refresh token and saw this question. And implemented this solution to my code but nothing changed.
Edit 4 : I tried to get access token according to this answer at android application and send it to app server. I'm taking the code as before I did :
GoogleSignInAccount acct = result.getSignInAccount();
code = acct.getServerAuthCode();//sending this code to AsyncTask to get access token
my function to get Access Token:
private void getAccessToken()throws GoogleAuthException, IOException{
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
List<String> scopes = new LinkedList<String>();
scopes.add("https://www.googleapis.com/auth/calendar");
scopes.add("https://www.googleapis.com/auth/calendar.readonly");
scopes.add("https://www.googleapis.com/auth/urlshortener");
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(transport, jsonFactory, client_id, client_secret, scopes).build();
try{
GoogleTokenResponse res = flow.newTokenRequest(code).execute();
accessToken = res.getAccessToken();
}catch(IOException e){
}
at the php server side I changed user-example.php file little bit as below because I have the access token now:
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setAccessType("offline");
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/urlshortener");
$service = new Google_Service_Urlshortener($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
$client->setAccessToken('{"access_token":"'. $access_token .'","token_type":"Bearer","expires_in":3600,"created":'. time() .'}');
if ($client->getAccessToken() && isset($_GET['url'])) {
$url = new Google_Service_Urlshortener_Url();
$url->longUrl = $_GET['url'];
$short = $service->url->insert($url);
$_SESSION['access_token'] = $client->getAccessToken();
But now I'm getting below error:
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/urlshortener/v1/url: (403) Insufficient Permission' in C:\wamp\www\google-php\src\Google\Http\REST.php on line 110
I was getting Insufficient Permission error after I started to use GoogleAuthorizationCodeFlow to get access token as I mentioned in my OP. And then I tried to add Calendar scope to GoogleApiClient.Builder(this) but I get error like I can't add scope if I add Auth.GOOGLE_SIGN_IN_API because I had added Auth.GOOGLE_SIGN_IN_API to GoogleApiClient.Builder. So this time I tried to add the scope to GoogleSignInOptions.Builder and it is working now. I'm able to get both refresh token and access token. Below code solved my problem:
GoogleSignInOptions gso = state.getGso();
if(gso == null){
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(new Scope("https://www.googleapis.com/auth/calendar"))
.requestIdToken(getString(R.string.server_client_id))
.requestEmail()
.requestServerAuthCode(getString(R.string.server_client_id), false)
.requestProfile()
.build();
}