PayPal Rest API - End Point Used - paypal

In my Dev environment, I can correctly use the Rest API to the sandbox site:
$sdkConfig = array(
"mode" => 'sandbox'
);
$cred = new OAuthTokenCredential(
$SANDBOX_clientId,
$SANDBOX_clientSecret
);
$access_token = $cred->getAccessToken($sdkConfig);
When using the same code with Live Keys and a verified Live account:
$sdkConfig = array(
"mode" => 'live'
);
$cred = new OAuthTokenCredential(
$LIVE_clientId,
$LIVE_clientSecret
);
$access_token = $cred->getAccessToken($sdkConfig);
I get this error:
Http response code 401 when accessing https://api.sandbox.paypal.com/v1/oauth2/token
How does the PayPal REST API know which endpoint to access?
I am not specifying the endpoint in the sandbox or live calls and am not using a bootstrap or ini file. The account is verified and approved.

The best way I would recommend is to create an ApiContext object similar to shown at https://gist.github.com/jaypatel512/a2b037ab5ddc51fa7280
<?php
// 1. Autoload the SDK Package. This will include all the files and classes to your autoloader
require __DIR__ . '/PayPal-PHP-SDK/autoload.php';
// 2. Provide your Secret Key. Replace the given one with your app clientId, and Secret
// https://developer.paypal.com/webapps/developer/applications/myapps
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS', // ClientID
'EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL' // ClientSecret
)
);
// Step 2.1 : Between Step 2 and Step 3
$apiContext->setConfig(
array(
'mode' => 'live',
'log.LogEnabled' => true,
'log.FileName' => 'PayPal.log',
'log.LogLevel' => 'FINE'
)
);
// 3. Lets try to save a credit card to Vault using Vault API mentioned here
// https://developer.paypal.com/webapps/developer/docs/api/#store-a-credit-card
$creditCard = new \PayPal\Api\CreditCard();
$creditCard->setType("visa")
->setNumber("4417119669820331")
->setExpireMonth("11")
->setExpireYear("2019")
->setCvv2("012")
->setFirstName("Joe")
->setLastName("Shopper");
// 4. Make a Create Call and Print the Card
try {
$creditCard->create($apiContext);
echo $creditCard;
}
catch (\PayPal\Exception\PayPalConnectionException $ex) {
echo $ex;
}

Related

Unable to get Response Parameters in Notification and Success url SOFORT API

public function sofyAction()
{
$args = [ 'config_key' => $this->getConfigKey() ];
$sofy = new Api($args);
$helper = $this->getServiceLocator()->get('ViewHelperManager')->get('ServerUrl');
$successUrl = $helper($this->url()->fromRoute('sofort_response'));
$params = [
'amount' => 1500,
'currency_code' => 'EUR',
'reason' => 'Vouhcer Order',
'success_url' => $successUrl,
'customer_protection' => false,
'notification_url' => 'MY_PRIVATE_RESPONSE_URL',
];
$trans = $sofy->createTransaction($params);
return $this->redirect()->toUrl($trans['payment_url']);
}
How to get response and transaction ID as given it API document in Notification URL and on success URL too , please unable to find any help or guide for it ?
The easiest way is to let Payum do notification related job for you. To do so you either:
have to create manually a notification token using Payum's token factory (I am not sure it is present in the Zend module, it is quite old). Use the token as notification_url. Nothing more. Sofort will send a request to that url and Payum does the rest.
Make sure the token factory is passed to a gateway object and later is injected to capture action object. Leave the notification_url field empty and Payum will generate a new one.
use your own url as notification one and add there all the info you need (as a query string). I wouldn't recommend it since you expose sensitive data and once could try to exploit it.
I solved it this way by appending ?trx=-TRANSACTION- with success and notification url and than in response i recieved Transaction id as parameter and later loaded TransactionData with that transactionId . Payum Token way wasn't working for me ! Obiously had to use its config key to create Payum/Sofort/Api isnstance,
REQUEST:
$args = [ 'config_key' => $sofortConfigKey ];
$sofortPay = new Api($args);
// ?trx=-TRANSACTION- will append transacion ID as response param !
$params = [
'amount' => $coupon['price'],
'currency_code' => $coupon['currency'],
'reason' => $coupon['description'],
'success_url' => $successUrl.'?trx=-TRANSACTION-',
'abort_url' => $abortUrl.'?trx=-TRANSACTION-',
'customer_protection' => false,
'notification_url' => '_URL_'.'?trx=-TRANSACTION-',
];
$transactionParams = $sofortPay->createTransaction($params);
return $this->redirect()->toUrl($transactionParams['payment_url']);
RESPONSE:
$args = [ 'config_key' => $configKey ];
$sofy = new Api( $args );
$transNumber = $this->getRequest()->getQuery('trx');
$fields = $sofy->getTransactionData($transNumber);
Took help from API document. Payum documentation is worst. SOFORT API DOC

Facebook Marketing API and Ads Insight Access

I'm building a small program that works with various APIs to automate reporting services we offer some clients.
One of the things we report on is Facebook Ads performance.
I've been building out this program using the Facebook Marketing API & Ads Insight APi https://developers.facebook.com/docs/marketing-apis
I've gone through the whole process of setting up a Facebook 'App' and getting the relevant app tokens.
However, I've hit a wall since development access only allows for 5 Ad Accounts.
To apply for basic access, the marketing API is asking for the development platform and a whole bunch of other things that aren't relevant to my program. I'm not building an 'app' intended for public release in the traditional sense; rather, I just want to integrate with these APIs on a basic level to automate some internal tasks.
It seems mind-boggling to me that I wouldn't be able to do something like this, but this is what the Facebook documentation seems to be suggesting.
If anyone else has familiarity with this kind of issue, I'd love to know if there is a workaround.
Submit your app for review to get more than 10 ad accounts. Use the "Platform" of Website. Select Native or desktop app; app secret NOT embedded in the client. The rest of it can be mostly ignored, but you will need to include some screen shots of your app and a description of how it works and what it does. A real human will review it, and you can get help in the Facebook Developers group here:
https://www.facebook.com/groups/fbdevelopers
Youwill get a pass/fail only...no comments. Don't be surprised if they reject it first time around. Do not resubmit and hope for a better response the second time around -- they'll eventually lock you out for a few days. Post a help question to the group.
Derks, I currently am building dashboard with over 40 clients and I am able to display everyone of them and their insights data etc. with basic development level. I have code if you want to take a look only thing I am trying to accomplish now is making a date range picker but, you are more than welcome enough to take a look at what I have just to get a general idea.
Here are the Use objects from Facebook
<?php
require_once __DIR__ . '/vendor/autoload.php';
use FacebookAds\Api;
use FacebookAds\Object\AdUser;
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
use FacebookAds\Object\Campaign;
use FacebookAds\Object\Fields\AdsInsightsFields;
use FacebookAds\Object\Ad;
use FacebookAds\Object\Fields\AdSetFields;
use FacebookAds\Object\AdCampaign;
use FacebookAds\Object\Fields\AdFields;
use FacebookAds\Object\Fields;
use FacebookAds\Object\Fields\AdImageFields;
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\AdSet;
use FacebookAds\Object\AdCreative;
use FacebookAds\Object\Fields\AdCreativeFields;
use FacebookAds\Object\Fields\AdCreativePhotoDataFields;
use FacebookAds\Object\AdCreativeLinkData;
use FacebookAds\Object\Fields\AdCreativeLinkDataFields;
use FacebookAds\Object\Fields\CampaignFields;
use FacebookAds\Object\Page;
use FacebookAds\Object\Fields\AdPreviewFields;
use FacebookAds\Object\Values\AdPreviewAdFormatValues;
use FacebookAds\Object\AdVideo;
?>
Here is the general code I am trying
<?php
// Init PHP Sessions
session_start();
$fb = new Facebook([
'app_id' => 'xxxxxxxxx',
'app_secret' => 'xxxxxxxxxxx',
]);
$helper = $fb->getRedirectLoginHelper();
if (!isset($_SESSION['enter api key here'])) {
$_SESSION['enter api key here'] = null;
}
if (!$_SESSION['enter api key here']) {
$helper = $fb->getRedirectLoginHelper();
try {
$_SESSION['enter api key here'] = (string) $helper->getAccessToken();
} catch(FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}
if ($_SESSION['enter api key here']) {
//echo "You are logged in!";
// Initialize a new Session and instantiate an API object
Api::init(
'xxxxxxxxx', // App ID
'xxxxxxxxx', //app_secret
$_SESSION['enter api key here'] // Your user access token
);
?>
<div id="fbdata"></div> <?php
$account = new AdAccount('act_xxxxxxxxxx');
$params = array(
'date_preset'=> 'last_28d',
'thumbnail_width' => 200,
'thumbnail_height' => 150,
'level' => 'campaign',
'limit' => '15'
);
$fields = array(
AdsInsightsFields::CAMPAIGN_NAME,
AdsInsightsFields::CAMPAIGN_ID,
AdsInsightsFields::IMPRESSIONS,
AdsInsightsFields::CLICKS,
AdsInsightsFields::REACH,
AdsInsightsFields::SPEND,
AdsInsightsFields::CPM,
AdsInsightsFields::CPC,
AdsInsightsFields::ACTIONS,
);
$field = array(
AdCreativeFields::TITLE,
AdCreativeFields::THUMBNAIL_URL,
AdCreativeFields::BODY,
);
$params1 = array(
'time_range' => array(
'since' => (new \DateTime($beginDate))->format('Y-m-d'),
'until' => (new \DateTime($lastDate))->format('Y-m-d'),
),
'thumbnail_width' => 200,
'thumbnail_height' => 150,
'level' => 'ad',
'limit' => '5'
);
$adcreatives = $account->getAdCreatives($field, $params1);
?>
<table class="fbtable">
<tr>
<th>Title</th>
<th>Ad Image</th>
<th>Ad Body</th>
</tr>
<?php
foreach($adcreatives as $t2){
echo"<tr>
<td>$t2->title</td>
<td><img src='$t2->thumbnail_url'/></td>
<td>$t2->body</td>
</tr>";
}
$insights = $account->getInsights($fields, $params);?>
<table class="fbtable">
<tr>
<th>Campaign ID</th>
<th>Campaign Name</th>
<th>Impressions</th>
<th>Clicks</th>
<th>Reach</th>
<th>Spend</th>
<th>Total Actions</th>
<th>CPM</th>
<th>CPC</th>
</tr>
<?php
foreach($insights as $i) {
$impress = number_format((float)$i->impressions);
$reach = number_format((float)$i->reach);
$totalAction = number_format((float)$i->actions);
$cpc = number_format($i->cpc, 2, '.', '');
$cpm = number_format($i->cpm, 2, '.', '');
echo"<tr class='fbtable'>
<td>$i->campaign_id</td>
<td>$i->campaign_name</td>
<td>$impress</td>
<td>$i->clicks</td>
<td>$reach</td>
<td>$$i->spend</td>
<td>$totalAction</td>
<td>$$cpm</td>
<td>$$cpc</td>
</tr>";
}
}else {
$permissions = ['ads_management'];
$loginUrl = $helper->getLoginUrl('http://where you want login to be.com', $permissions);
echo 'Log in with Facebook';
}
?>
I will help much as I can #Derks and I believe the only thing you may need to do is figure out way for the program or whatever your building know who is who.

Facebook php-sdk v4 PhalconPHP integration

I'm currently trying to integrate the lastest Facebook php sdk into a Phalcon project but I'm not having much luck.
I can get the SDK to work in a standalone project but the exact same code fails when integrated into a Phalcon project (either as a service or directly in a Controller).
The issue seems to be that the facebook redirect helper creates a "state" property which is appended to a loginUrl and then stored in a session. When a user is redirected back to my site after signing in, it checks this property against a querystring value. The state property is only generated and stored whenever you display the login url via the redirectHelpers getLoginUrl() method. Somehow, when I integrate this in Phalcon the session variable and the $_GET parameter never seem to match up. The simple example which works is as follows
// lots of requires
Facebook\FacebookSession::setDefaultApplication($appId,$secret);
$helper = new Facebook\FacebookRedirectLoginHelper('http://'.$_SERVER['HTTP_HOST'] .'/');
// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// validate the access_token to make sure it's still valid
try {
if ( !$session->validate() ) {
$session = null;
}
} catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
} // end if isset($_SESSION)
if ( !isset( $session ) || $session === null ) {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
// handle this better in production code
print_r( $ex );
} catch( Exception $ex ) {
// When validation fails or other local issues
// handle this better in production code
print_r( $ex );
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
$session = new FacebookSession( $session->getToken() );
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject()->asArray();
// print profile data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
// print logout url using session and redirect_uri (logout.php page should destroy the session)
echo 'Logout';
} else {
// show login url
echo 'Login'; // this line would generate a new state
}
When I try using this exact same code in a controller in a phalcon project (or by setting "$me" up in the $di), the state check always fails even though I'm not generating a new login url. The only other difference is that in the simple project I require all the facebook files using require_once but in the Phalcon project I use
$loader->registerNamespaces(
array(
"Facebook" => __DIR__ . '/../../vendor/facebook/php-sdk-v4/src/Facebook/'
)
);
but replacing that with the requires doesn't seem to have an effect.
Anyone got any clues?
I've got it working by using registerClasses not registerNamespaces - but using v3.2.x so not a v4.
$loader->regeisterNamespaces( /* Projects' classes */ )
->registerClasses(array(
'Facebook' => __DIR__ . '/../../vendor/facebook/php-sdk/src/facebook.php'
))
->register();
ps.: Im using composer to load FacebookSDK so I have different path than yours.
Then I'm using it in Controller ordinary without using $di,
protected function getFacebook()
{
if (!$this->facebook) {
$this->facebook = new Facebook(array(
'appId' => $this->config->social->facebook->appId,
'secret' => $this->config->social->facebook->secret,
'fileUpload' => false,
'allowSignedRequest' => false,
));
}
return $this->facebook;
}
I've worked this one out. The issue was that the browser was automatically making a request to /favicon.ico as well,as I didn't have a favicon.ico this then rendered the default indexAction again and as such this was causing the getLoginUrl() method to fire again generating a new state. The simple fix is to just create a favicon, or define the error handling route for files not there (I was just using the boilerplate from the phalcon dev tools initially)

Zend Gmail Oauth: How to get authenticated user profile?

I am using Zend Gmail Oauth 1.0 for implementing login with Gmail feature.
After successful authentication, how can I get authenticated user's profile, specifically user's unique gmail id? Here is the code:
$THREE_LEGGED_SCOPES = array('https://mail.google.com/',
'https://www.google.com/m8/feeds');
$options = array(
'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
'version' => '1.0',
'consumerKey' => $THREE_LEGGED_CONSUMER_KEY,
'consumerSecret' => $THREE_LEGGED_CONSUMER_SECRET_HMAC,
'callbackUrl' => getCurrentUrl(),
'requestTokenUrl' => 'https://www.google.com/accounts/OAuthGetRequestToken',
'userAuthorizationUrl' => 'https://www.google.com/accounts/OAuthAuthorizeToken',
'accessTokenUrl' => 'https://www.google.com/accounts/OAuthGetAccessToken'
);
if ($THREE_LEGGED_SIGNATURE_METHOD == 'RSA-SHA1') {
$options['signatureMethod'] = 'RSA-SHA1';
$options['consumerSecret'] = new Zend_Crypt_Rsa_Key_Private(
file_get_contents(realpath($THREE_LEGGED_RSA_PRIVATE_KEY)));
} else {
$options['signatureMethod'] = 'HMAC-SHA1';
$options['consumerSecret'] = $THREE_LEGGED_CONSUMER_SECRET_HMAC;
}
$consumer = new Zend_Oauth_Consumer($options);
/**
* When using HMAC-SHA1, you need to persist the request token in some way.
* This is because you'll need the request token's token secret when upgrading
* to an access token later on. The example below saves the token object
* as a session variable.
*/
if (!isset($_SESSION['ACCESS_TOKEN'])) {
if (!isset($_SESSION['REQUEST_TOKEN'])) {
// Get Request Token and redirect to Google
$_SESSION['REQUEST_TOKEN'] = serialize($consumer->getRequestToken(array('scope' => implode(' ', $THREE_LEGGED_SCOPES))));
$consumer->redirect();
} else {
// Have Request Token already, Get Access Token
$_SESSION['ACCESS_TOKEN'] = serialize($consumer->getAccessToken($_GET, unserialize($_SESSION['REQUEST_TOKEN'])));
header('Location: ' . getCurrentUrl(false));
exit;
}
} else {
// Retrieve mail using Access Token
$accessToken = unserialize($_SESSION['ACCESS_TOKEN']);
}
near as I can tell you can't.
Gmail doesn't have an api just a read only feed.
However if you want that feed the scope url is:
https://mail.google.com/mail/feed/atom/
There are some api's for working with gmail accounts in the context of Google Apps.

Linkedin OAuth and Zend retrieving Acces Token returns 'Error in HTTP request'

Answer + new question
I found out that the code below works just fine on a LIVE server. LinkedIN blocked all requests from localhost.
That established; Does anybody know how to test an application from localhost with LinkedIN OAuth? Because doing this on a live server sucks!
Old Question
I'm trying to connect with Zend_OAuth to LinkedIN. This code used to work, but now it returns an error in http request while I'm trying to retrieve an access token.
Tried checking the LinkedIN api, but the code still seems valid. Tried several scripts but all with the same result.
The config is setup in the preDispatch of my controller
$this->configLinkedin = array(
'version' => '1.0',
'siteUrl' => 'http://'.$_SERVER['HTTP_HOST'].$this->view->baseUrl(false).'/news/index/connectlinkedin',
'callbackUrl' => 'http://'.$_SERVER['HTTP_HOST'].$this->view->baseUrl(false).'/news/index/connectlinkedin',
'requestTokenUrl' => 'https://api.linkedin.com/uas/oauth/requestToken',
'userAuthorisationUrl' => 'https://api.linkedin.com/uas/oauth/authorize',
'accessTokenUrl' => 'https://api.linkedin.com/uas/oauth/accessToken',
'consumerKey' => 'XXX',
'consumerSecret' => 'XXX'
);
And the code in the action to connect to linkedIN is
$this->consumer = new Zend_Oauth_Consumer($this->configLinkedin);
if(!empty($_GET) && isset($_SESSION['LINKEDIN_REQUEST_TOKEN']))
{
$token = $this->consumer->getAccessToken($_GET, unserialize($_SESSION['LINKEDIN_REQUEST_TOKEN']));
// Use HTTP Client with built-in OAuth request handling
$client = $token->getHttpClient($this->configLinkedin);
// Set LinkedIn URI
$client->setUri('https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url)');
// Set Method (GET, POST or PUT)
$client->setMethod(Zend_Http_Client::GET);
// Get Request Response
$response = $client->request();
$this->NewsService->TokenSocialMedia(
$token,
'linkedin',
serialize($response->getBody())
);
$_SESSION['LINKEDIN_REQUEST_TOKEN'] = null;
$this->_helper->flashMessenger(array('message' => $this->view->translate('The CMS is successfully connected to your linkedin account'), 'status' => 'success'));
$this->_helper->redirector('settings#settingSocial', 'index');
}
else
{
$token = $this->consumer->getRequestToken();
$_SESSION['LINKEDIN_REQUEST_TOKEN'] = serialize($token);
$this->consumer->redirect();
}
What am I missing or doing wrong? I use a similair setup for Twitter and that works fine.
UPDATE 20 September 211
I found out that this rule is returning the error:
$token = $this->consumer->getRequestToken();
I'm still clueless why, and reading the linkedin api doesn't help a bit. Will keep you posted.
I got similar problem and after adding openssl extension it was solved
try adding to php.ini this line:
extension=php_openssl.dll
I got the same issue, try to turn off ssl before asking the new consumer :
$httpConfig = array(
'adapter' => 'Zend\Http\Client\Adapter\Socket',
'sslverifypeer' => false
);
$httpClient = new HTTPClient(null, $httpConfig);
OAuth::setHttpClient($httpClient);