Sending Money with Dwolla's API and using PHP to do it? - php

Hello everyone I'm back again, In my last post I was attempting to use the SOAP api (Integrating Dwolla with PHP with their API) but I found out the SOAP API is deprecated and apparently Dwolla has more efficient way such as the REST/oAuth2.0 which is why I'm here today asking how to use the rest API as its been almost 2 weeks and I'd really like to learn this.
First off I'll say that I've successfully been able to get an access_token I have no problem doing that. The issue is that when I try to use an a Send Endpoint(https://www.dwolla.com/developers/endpoints/accountapi/send) basically trying to send money to and account. My exact issue is that I can never get a successful response; only false or error message responses.
So on the index page I have "Add funds to your account" link. Users will click that link and it will take them to the Dwolla Page that will accept them to Sign in to their Dwolla account an then accept the permissions the website is asking for. After the user presses "Accept" it will redirect to the selected URL that I chose and send back an access_token to use for authorization purposes. Here is my code (This is the page that Dwolla redirects too and sends the access_token too)
<?php
//Define variables
$key = 'redacted';
$secret = 'redacted';
$dwolla_client_id = urlencode($key);
$dwolla_secret_key = urlencode($secret);
$code = urlencode($_GET["code"]);
//get token
$retireve_token = file_get_contents("https://www.dwolla.com/oauth/v2/token?client_id=".$dwolla_client_id."&client_secret=".$dwolla_secret_key."&grant_type=authorization_code&redirect_uri=http://localhost/purchase_order.php&code=".$code);
$decoded_json = json_decode($retireve_token, true);
var_dump($decoded_json);
if($decoded_json["access_token"]){
$arr = '{
"oauth_token": "'.$decoded_json["access_token"].'",
"fundsSource": "balance",
"pin": "1111",
"notes": "Payment for services rendered",
"amount": 1.01,
"destinationId": "812-111-1111",
"assumeCosts": false,
"facilitatorAmount": 0,
"destinationType": "dwolla"
}';
$opts = array('http'=>array('method'=>"POST",'content'=> $arr, 'header' => 'Content-Type: application/json'));
$ctx = stream_context_create($opts);
$send_request = file_get_contents('https://www.dwolla.com/oauth/rest/accountapi/send', false, $ctx);
var_dump(json_decode($send_request));
}
?>
I receive messages like this for example
array(1) { ["access_token"]=> string(50)
"redacted" } Warning:
file_get_contents(https://www.dwolla.com/oauth/rest/accountapi/send):
failed to open stream: HTTP request failed! HTTP/1.1 503 Service
Unavailable in /home/swiftbitcoins/purchase_order.php on line 47 NULL

what you are trying to make is a get request whereas Dwolla documentation refers to this as post request.
better you can do is user their php Library with built in methods to make calls. this is a standard library for making restful calls and much better than writing the way you have written in the code snippet above.
https://github.com/Dwolla/dwolla-php

Related

“Non-200 response code during CRC GET request”

I want t register a webhook. I have this PHP code in my webhook endpoint URL:
<?php
// Example app consumer secret found in apps.twitter.com
const APP_CONSUMER_SECRET = 'xxx';
// Example token provided by incoming GET request
$token = $_GET['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);
}
// prints result
echo get_challenge_response($token);
If I try it directly (with the browser itself, i.e.) I get this response:
{"response_token":"sha256=VvHK6oEH4CHfnP9ImMmidtjTHGy48DuACxR6TSYyCcQ="}
Which makes me think it works properly, I also receive a 200 status code. But when I try to call the Twitter API to register the webhook I always get this error message:
{
"errors": [
{
"code": 214,
"message": "Non-200 response code during CRC GET request (i.e. 404, 500, etc)."
}
]
}
Whether I try it with Insomnia, Postman, or even the Account Activity Dashboard. It makes no sense because if I go to my browser and go to my PHP script, I receive good response.
Anyone know what is going on and how can I fix it?
Thanks!
Twitter is saying that your script is returning something other than a HTTP 200 response code. It might indicate there is an error happening during the Twitter request.
Make sure the webhook URL is correct.
Log the request coming from Twitter and make sure you are getting the expected input.
Check your logs for errors.
Try forcing the response code:
http_response_code(200);

How to access the Microsoft Graph API data for the local user

I'm trying to setup a web app that will verify if a particular user is part of a domain, and since we have standardized usernames on our domain I thought to just get their email and do string manipulation to check.
However, now that I've got the Microsoft Graph API working (by which I mean I have the Bearer token and am trying to request 'graph.microsoft.com/v1.0/users' I am getting an 'Insufficient privileges to complete the operation' error.
I want to access the data relative to the user who just signed in and I now have an access token for. Am I using the wrong endpoint or am I just overlooking something. There is limited example of what I wish to do and I've re-written an outdated example from which I based my code off.
$checkDomain = curl_init();
curl_setopt_array($checkDomain, [
CURLOPT_URL => "https://graph.microsoft.com/v1.0/users",
CURLOPT_HTTPHEADER => array("Authorization: Bearer " . $access_token),
CURLOPT_RETURNTRANSFER => 1,
]);
$result2 = curl_exec($checkDomain);
if ($result2 == false) {
die("Result failed");
} else {
echo("checkDomain: ");
}
echo($result2);
$result2 = json_decode($result2);
// ready for str manipulation outside
curl_close($checkDomain);
the users endpoint is used when logged in as a tenant/app without user. When logged in a user the me endpoint is used.
From the /me endpoint you can examine the json that comes back and look at the mail element that comes back and use that to check against the domain.

Can only get access token for QuickBooks API once

I'm using PHPoAuthLib in order to connect to the QuickBooks API per their example
When I follow their example, the first request that I make to the API works perfectly:
$result = json_decode($quickbooksService->request($url));
echo 'result: <pre>' . print_r($result, true) . '</pre>';
However in their example they use $_GET['oauth_token'] and $_GET['oauth_verifier'] to request an access token, and these values are only available on the $_GET server variable during the single callback from QuickBooks Online immediately after my app has been authorized.
For future requests there are no such examples on PHPoAuthLib's docs, so I tried a quick homebrew solution:
Save the response from QBO somewhere
if (!empty($_GET['oauth_token']) {
file_put_contents("token.txt", json_encode([
'oauth_token' => $_GET['oauth_token'],
'oauth_verifier' => $_GET['oauth_verifier'],
'realm_id' => $_GET['realmId']
]));
}
Use that response again later
$token = json_decode(file_get_contents("token.txt"));
$quickbooksService->requestAccessToken(
$token->oauth_token,
$token->oauth_verifier
// $token->getRequestTokenSecret() is not necessary - it will be automatically populated
);
// At this point my app crashes and return a 500 error
// Further code does not run
The error I receive is:
TokenResponseException in StreamClient.php line 68:
Failed to request resource. HTTP Code: HTTP/1.1 401 Unauthorized
Remember that the token and verifier work perfectly if I use them immediately after the app is authorized. If I save them to a file and attempt to re-use them 30 seconds later, this happens.
I think it might be a fundamental misconception about OAuth 1.0
I don't think what you have is a correct OAuth implementation. Have you read the OAuth spec and implemented as it's defined there?
Once you have a request token and a verifier, you use those to get an access token.
That access token is then good for 6 months.
It looks like you're trying to use a short-lived request token to continually fetch access tokens instead. That won't work.
i.e. If you're doing this everytime you want to make another request:
$quickbooksService->requestAccessToken(
Then you're doing something wrong. You should be doing that ONCE every 6 months, and that's it.
Working code here:
https://github.com/consolibyte/quickbooks-php/blob/master/QuickBooks/IPP/IntuitAnywhere.php
https://github.com/consolibyte/quickbooks-php/blob/master/QuickBooks/IPP/OAuth.php
https://github.com/consolibyte/quickbooks-php
Spec is here:
http://oauth.net/core/1.0a/#auth_step3

Receiving HTTP 401 Unauthorized when making a Google plus API call

I'm trying to get the list of all my friends from the Google plus via API. The user on whose behalf I'm doing this operation previously authorized my request and I got the auth token. I've tried the following code in php:
function CallAPI() {
$opts = array(
"http" => array(
"method" => "GET"
)
);
$url = 'https://www.googleapis.com/plus/v1/people/me/people/visible?key=XXXX';
$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);
var_dump($response);
}
but I keep receiving HTTP request failed! HTTP/1.0 401 Unauthorized. How can I prove that the user authorized my operations or what am I doing wrong?
Any help is much appreciated.
You need to authenticate the user to use the special keyword "me" so using your simple API key will not work (assuming the key passed is your simple key). Instead, you need to get an access token and pass that.
For a great example of how to do this in PHP using the PHP client library, try the quickstart:
https://developers.google.com/+/quickstart/php
If you are already getting an access token, you can call tokeninfo passing access token to get more information about who the user is associated with it:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=ya29.xxxxxxxx...
At this point, you could call:
'https://www.googleapis.com/plus/v1/people/[useridfromaccesstoken]/people/visible?key=XXXX';
To verify that your API key is correct but I would recommend using the client library as demonstrated in the quickstart sample.

How to get responses other than timestamp and num_bytes from TripIt API?

I have got a successful oauth TripIt granting process using the same methodology that is used to connect and authenticate users against the LinkedIn and Twitter APIs in PHP (PECL Oauth etc).
However, whenever when I do a valid request (ie a 200 response... no 401 nor 404), all I get in response is:
<Response><timestamp>1301411027</timestamp><num_bytes>80</num_bytes></Response>
I want to list the authenticated user's profile and trip data... The API docs (the pdf) is a bit sketchy on how to do this when the actual user id isn't known, but here are the queries I have attempted:
https://api.tripit.com/v1/list/trip
https://api.tripit.com/v1/list/trip/traveler/true
https://api.tripit.com/v1/get/profile
All returning the same response (as part of the oauth class "last response" method). This is where the LinkedIn API response contents can be found... so what is going on with TripIt? :P
It took a bit of experimenting, but here's an example of one that appears to be working to return data.
$response = $TripIt->_do_request('get/profile');
EDIT:
This one is likely the preferred method.
$response = $TripIt->_do_request('get', 'profile');
I've gone one step further and thrown it into an XML parser.
$response = $TripIt->_do_request('get', 'profile');
$profile = new SimpleXMLElement($response);
Here is one I'm using to get past trips. That third parameter is the one to use for filters.
$response = $TripIt->_do_request('list', 'trip', array('past'=>'true' );
$trips = new SimpleXMLElement($response);

Categories