Paypal REST Api implmentation - php

I am new to curl so I am using code found on the Paypal Developer blog and I am having a hard time getting it to work for me. Here is the code I am using
class paypal {
private $access_token;
private $token_type;
/**
* Constructor
*
* Handles oauth 2 bearer token fetch
* #link https://developer.paypal.com/webapps/developer/docs/api/#authentication--headers
*/
public function __construct(){
$postvals = "grant_type=client_credentials";
$uri = PAYMENT_URI . "v1/oauth2/token";
$auth_response = self::curl($uri, 'POST', $postvals, true);
$this->access_token = $auth_response['body']->access_token;
$this->token_type = $auth_response['body']->token_type;
}
/**
* cURL
*
* Handles GET / POST requests for auth requests
* #link http://php.net/manual/en/book.curl.php
*/
private function curl($url, $method = 'GET', $postvals = null, $auth = false){
$ch = curl_init($url);
//if we are sending request to obtain bearer token
if ($auth){
$headers = array("Accept: application/json", "Accept-Language: en_US");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, CLIENT_ID . ":" .CLIENT_SECRET);
curl_setopt($ch, CURLOPT_SSLVERSION, 3);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
//if we are sending request with the bearer token for protected resources
} else {
$headers = array("Content-Type:application/json", "Authorization:{$this->token_type} {$this->access_token}");
}
$options = array(
CURLOPT_HEADER => true,
CURLINFO_HEADER_OUT => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_VERBOSE => true,
CURLOPT_TIMEOUT => 10
);
if ($method == 'POST'){
$options[CURLOPT_POSTFIELDS] = $postvals;
$options[CURLOPT_CUSTOMREQUEST] = $method;
}
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$header = substr($response, 0, curl_getinfo($ch,CURLINFO_HEADER_SIZE));
$body = json_decode(substr($response, curl_getinfo($ch,CURLINFO_HEADER_SIZE)));
curl_close($ch);
return array('header' => $header, 'body' => $body);
}
// Function for Processing Payment
function process_payment($request) {
$postvals = $request;
$uri = PAYMENT_URI . "v1/payments/payment";
return self::curl($uri, 'POST', $postvals);
}
}
if (isset($_SESSION['payment_type']) && ($_SESSION['payment_type'] == 'paypal')) { // User has chosen to pay with Paypal.
// Retrive Shopping cart contents
$r = mysqli_query($dbc, "CALL get_shopping_cart_contents('$uid')");
$request = array(
'intent' => 'sale',
'redirect_urls' => array(
'return_url' =>'http://store.example.com/final',
'cancel_url' =>'http://store.example.com/payment'
),
'payer' => array(
'payment_method' =>'paypal'
),
'transactions' => array(
'amount' => array(
'total' =>''.number_format($order_total,2).'',
'currency' =>'USD',
'details' => array(
'subtotal' =>''.number_format($subtotal,2).'',
'shipping' =>''.number_format($shipping,2).''
),
'item_list' => array(
)
),
'description' =>'Mike and Maureen Photography - Order ID #'.$order_id.''
)
);
while ($items = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$newitems = array(
'quantity' =>''.$items['quantity'].'',
'name' =>''.$items['name'].'',
'price' =>''.get_price($items['price'],$items['sales_price']).'',
'currency' =>'USD'
);
$request['transactions']['amount']['item_list']['items'][] = $newitems;
}
$request = json_encode($request);
process_payment($request);
}
I am good with php but this whole class, public/private stuff is throwing me off. Can I use this code without that or will it open me up to trouble? How do I run the process_payment function without it throwing an error. I am getting "Fatal error: Call to undefined function process_payment()"
Didnt I just define the function in the paypal class? I have read through the documentation on paypal and I cant get a grasp on what I am doing wrong. Any help would be great.

The function process_payment() is part of the paypal class. To call it, you will have to do one of the ways outlined here: https://stackoverflow.com/a/4216347/1715048

Related

Trying to turn wp_remote_request to curl php function with php to avoid to rely on wordpress

Here's my problem:
I need a curl call in order to use it from an environment outside WordPress.
The older code was:
public function post_api($path = '', $method = '', $body = '') {
$token = $this->get_token();
$headers = array(
'Accept' => 'application/json',
'Content-Type' => 'application/json; charset=utf-8',
'Connection' => 'Keep-Alive',
'Keep-Alive' => 'timeout=30, max=100',
'X-API-Key' => $token['key'],
'X-API-Hmac' => $token['token'],
);
$args = array(
'body' => $body,
'headers' => $headers,
'method' => strtoupper($method),
'sslverify' => false
);
$response = wp_remote_request($path, $args);
$body = array();
if (is_array($response) && isset($response['response']['code'])) {
//something with those data
}
return $body;
}
But now I need an universal curl call with php that can work outside wordpress (anywhere really). Something like this:
public function post_api($path = '', $method = '', $body = '') {
$token = $this->get_token();
$headers = array(
'Accept' => 'application/json',
'Content-Type' => 'application/json; charset=utf-8',
'Connection' => 'Keep-Alive',
'Keep-Alive' => 'timeout=30, max=100',
'X-API-Key' => $token['key'],
'X-API-Hmac' => $token['token'],
);
$args = array(
'body' => $body,
'headers' => $headers,
'method' => strtoupper($method),
'sslverify' => false
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $path);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt( $ch, CURLOPT_TIMEOUT,10);
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $body );
$head = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$response = [
'statusCode' => $httpCode,
'resp' => $head
];
curl_close($ch);
$body = array();
if (is_array($response) && isset($response['response']['code'])) {
//something with these data
}
return $body;
var_dump($body);
}
The problem is that it is returning something else:
Call using wp_remote_request
Query strings
0 baumiao#bau.com
emailAddress baumiao#bau.com
call using curl
Raw Content
--------------------------761ff1dfd8c7266e
Content-Disposition: form-data; name="0"
baumiao#bau.com
--------------------------761ff1dfd8c7266e--
Is there something that I missing? I read the curl documentation for PHP and I added all the setopt for that particular case, still, I'm not able to properly make the call.
Any help?

Get user e-mail from Linkedin (PHP)

I created a new application in Linkedin with r_basicprofile and r_emailaddress flags set to active.
I'm using the following PHP library (with CodeIgniter framework) to get user profile data. As you can see on the results, for some reason I can't get the e-mail address of user.
Someone know how to get the e-mail address ?
Thank you.
class linkedin
{
private $client_id = "123456789";
private $client_secret = "123456789012356";
public function in_redirect_url($redirect_url){
$state = $this->in_genState();
return "https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=$this->client_id&state=$state&scope=r_basicprofile&redirect_uri=$redirect_url";
}
public function in_genState()
{
return "123456789";
}
public function in_exchange_code_token($code)
{
// replace code with auth token
$url = 'https://www.linkedin.com/oauth/v2/accessToken';
$headers = [
'Content-type: application/x-www-form-urlencoded',
'Host: www.linkedin.com',
];
$fields = [
'grant_type' => 'authorization_code',
'code' => $code,
'redirect_uri' => base_url('login/linkedin'),
'client_id' => $this->client_id,
'client_secret' => $this->client_secret,
];
//url-ify the data for the POST
$fields_string = '';
foreach ($fields as $key => $value) {
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
// init curl handle
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
$response = json_decode($response);
return $response;
}
public function in_get_user_data($auth_token)
{
// replace code with auth token
$url = 'https://api.linkedin.com/v1/people/~:(email-address,id,first-name,last-name,location)';
$headers = [
'Host: api.linkedin.com',
'Connection: Keep-Alive',
];
$fields = [
'oauth2_access_token' => $auth_token,
'format' => 'json',
];
//url-ify the data
$fields_string = '';
foreach ($fields as $key => $value) {
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
// init curl handle
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url.'?'.$fields_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
$response = json_decode($response);
return $response;
}
}
And the following login code:
public function linkedin()
{
$code = $this->input->get('code');
$state = $this->input->get('state');
if (!$code) {
// redirect to linkedin login
$local_url = base_url('/login/linkedin');
header("Location: " . $this->linkedin->in_redirect_url($local_url));
die();
return;
}
// verify state
if ($state != $this->linkedin->in_genState()) {
echo 'Invalid request';
die(400);
}
$response = $this->linkedin->in_exchange_code_token($code);
if (property_exists($response, 'access_token')) {
echo 'Success !<br/>';
var_dump($response);
$access_token = $response->access_token;
var_dump($this->linkedin->in_get_user_data($access_token));
} else {
echo 'Error !<br/>';
var_dump($response);
}
}
This is an example result:
Success !
object(stdClass)[74]
public 'access_token' => string '*****' (length=179)
public 'expires_in' => string '5184000000' (length=10)
object(stdClass)[75]
public 'firstName' => string '***' (length=6)
public 'id' => string '***' (length=10)
public 'lastName' => string '***' (length=8)
public 'location' =>
object(stdClass)[76]
public 'country' =>
object(stdClass)[77]
public 'code' => string 'us' (length=2)
public 'name' => string 'United States' (length=6)
If you look in this section of your code:
public function in_redirect_url($redirect_url){
$state = $this->in_genState();
return "https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=$this->client_id&state=$state&scope=r_basicprofile&redirect_uri=$redirect_url";
}
Note that your &scope= parameter only requests r_basicprofile, and not r_emailaddress. If you want to rely on your LinkedIn application's default permissions to control what permission your app requests, you cannot specify a scope in your auth flow. If you do, it will override it - which is what's happening here, and you're overriding your scope to a value that does not include all of the member permissions that you think.

create post wordpress.com using rest api

I want to make php app to create post on wordpress.com using REST api.
I use this code:
<?php
$curl = curl_init( 'https://public-api.wordpress.com/oauth2/token' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_POSTFIELDS, array(
'client_id' => 12345,
'redirect_uri' => 'http://example.com/wp/test.php',
'client_secret' => 'L8RvNFqyzvqh25P726jl0XxSLGBOlVWDaxxxxxcxxxxxxx',
'code' => $_GET['code'], // The code fromthe previous request
'grant_type' => 'authorization_code'
) );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
$auth = curl_exec( $curl );
$secret = json_decode($auth);
$access_token = $secret->access_token;
$post = array(
'title'=>'Hello World',
'content'=>'Hello. I am a test post. I was created by
the API',
'date'=>date('YmdHis'),
'categories'=>'API','tags=tests'
);
$post = http_build_query($post);
$apicall = "https://public-api.wordpress.com/rest/v1/sites/mysite.wordpress.com/posts/new";
$ch = curl_init($apicall);
curl_setopt($ch, CURLOPT_HTTPHEADER, array
('authorization: Bearer ' . $access_token,"Content-Type: application/x-www-form-urlencoded;
charset=utf-8"));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
$return = curl_exec($ch);
echo "<pre>";
print_r($return);
exit;
?>
but I get this error:
{"error":"unauthorized","message":"User cannot publish posts"}
Can help me?
Thanks
Standard way to create posts is to use cookies and nonce.
However I found a more easy way to do it.
Install Basic-Auth plugin to your wordpress.
Create wordpress user with username admin and password admin (both credentials are insecure, used for demonstration purposes only)
Create post using code:
$username = 'admin';
$password = 'admin';
$rest_api_url = "http://my-wordpress-site.com/wp-json/wp/v2/posts";
$data_string = json_encode([
'title' => 'My title',
'content' => 'My content',
'status' => 'publish',
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $rest_api_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Authorization: Basic ' . base64_encode($username . ':' . $password),
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
if ($result) {
// ...
} else {
// ...
}
Note that in example above version 2 of REST API is used.
The answer is right that we can use the "Basic-Auth" plugin to make a Rest API request.
But, #vallez want to create a post on wordpress.com website.
And wordpress.com provide the oAuth support for authentication.
Recently I have created a post which demostrate about using the oAuth to create a post on wordpress.com. You can read the article at create the post on wordpress.com site using oAuth and Rest API
Below are the steps to successfully create a post with oAuth on wordpress.com.
Step 1: Add authentication details to get auth key.
$auth_args = array(
'username' => '',
'password' => '',
'client_id' => '',
'client_secret' => '',
'grant_type' => 'password', // Keep this as it is.
);
$access_key = get_access_key( $auth_args );
Below is the function get_access_key() which return the access key.
Step 2: Get Access Key.
/**
* Get Access Key.
*
* #param array $args Auth arguments.
* #return mixed Auth response.
*/
function get_access_key( $args ) {
// Access Token.
$curl = curl_init( 'https://public-api.wordpress.com/oauth2/token' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $args );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
$auth = curl_exec( $curl );
$auth = json_decode($auth);
// Access Key.
return $auth->access_token;
}
Step 3: Set post arguments and pass it create the post.
$post_args = array(
'title' => 'Test Post with oAuth',
'content' => 'Test post content goes here..',
'tags' => 'tests',
'post_status' => 'draft',
'categories' => 'API',
);
Step 4: Create a post with the access key.
Now, We have access key and the create post arguments. So, Lets pass them to function create_post().
create_post( $access_key, $post_args );
Step 5: Create a post with access key.
/**
* Create post with access key.
*
* #param string $access_key Access key.
* #param array $post_args Post arguments.
* #return mixed Post response.
*/
function create_post( $access_key, $post_args )
{
$options = array (
'http' => array(
'ignore_errors' => true,
'method' => 'POST',
'header' => array(
0 => 'authorization: Bearer ' . $access_key,
1 => 'Content-Type: application/x-www-form-urlencoded',
),
'content' => http_build_query( $post_args ),
),
);
$context = stream_context_create( $options );
$response = file_get_contents(
'https://public-api.wordpress.com/rest/v1/sites/YOURSITEID/posts/new/',
false,
$context
);
return json_decode( $response );
}

How to get a list of users of bugzilla project using XMLRPC after login

I'm looking for XMLRPC keywords to find out a list of users of a BUGZILLA project.
Here is my code, login works fine and im' able to use several keywords to find out what i need : Bug.search, Bug.fields.
public function loginBz($url,$login,$password,$getResult)
{
set_time_limit(0);
$URI = $url;
$xml_data = array(
'login' => $login,
'password' => $password,
'remember' => 1
);
$ch = curl_init();
$file_cookie = tempnam ("/tmp", "CURLCOOKIE");
$options = array(
//CURLOPT_VERBOSE => true,
CURLOPT_URL => $URI,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array( 'Content-Type: text/xml', 'charset=utf-8' )
);
curl_setopt($ch, CURLOPT_TIMEOUT,60);
curl_setopt_array($ch, $options);
$request = xmlrpc_encode_request("User.login", $xml_data);
// var_dump($request);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_COOKIEJAR, $file_cookie);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$server_output = curl_exec($ch); // Array( [id] => 1 ) for example
$response = xmlrpc_decode($server_output);
//print_r ($response);
if($getResult)
return $response;
else
return $ch;
}
public function getFieldsBz($product,$component,$ch){
$xml_data = array(
'product' => $product,
'component' => '$component'
);
$request = xmlrpc_encode_request("Bug.user", $xml_data); // create a request for filing bugs
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$server_output = curl_exec($ch); // Array( [id] => 1 ) for example
$response = xmlrpc_decode($server_output);
return $response;
}
I've been searching into BugZilla API but did not found what I need : List of Users for a product Bz.
Does anyone know which keyword I have to use in xmlrpc_encode_request(keyword,array_filter) ?
It would help :)
First there isn't a method called Bug.user, see https://www.bugzilla.org/docs/4.4/en/html/api/Bugzilla/WebService/Bug.html for a complete list.
There is a method called User.get, see https://www.bugzilla.org/docs/4.4/en/html/api/Bugzilla/WebService/User.html#get
There is a parameter called groups which may do what you want depending on how you setup Bugzilla security.
You can use https://xmlrpc.devzing.com/ to experiment or if you upgrade to Bugzilla 5.x you can use the new REST API. https://www.bugzilla.org/docs/5.0/en/html/api/Bugzilla/WebService/Server/REST.html

How do I send files in PHP via CURL? #filename won't work

I'm trying to send an image via POST using PHP's CURL methods.
I am sending the image to an API that expects the POST field 'photo_file' to be an image.
I set the 'photo_file' to # followed by the file name.
However, when I make the request the API receives the literal string '#filename' instead of the file contents.
Here is the relevant code:
Calling code:
$data = array(
'campaign_id' => $_POST['campaign_id'],
);
$img_source = realpath($img_source); // "/Users/andrew/Sites/roo/9699d27bb09fda3133701ca9af084e3d.jpg"
$response = $y->upload_photo($img_source, $data);
$y->upload_photo():
public function upload_photo($img_source, $data) {
$fields = array(
'campaign_id' => $data['campaign_id'],
'photo_file' => '#' . $img_source
);
return $this->request('photos', $fields, 'post');
}
$this->request() (relevant parts):
public function request($function, $fields = array(), $method = 'get') {
$ch = curl_init();
$url = $this->host . $function;
$curlConfig = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => array('Accept: application/json', 'Expect:'),
CURLOPT_VERBOSE => 1,
CURLOPT_HEADER => 1,
);
if ($method == 'post') {
$curlConfig[CURLOPT_POST] = 1;
$curlConfig[CURLOPT_POSTFIELDS] = true;
$curlConfig[CURLOPT_POSTFIELDS] = $fields;
}
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
list($header_blob, $body) = explode("\r\n\r\n", $result, 3);
$this->http_status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return json_decode($body);
}
The API is returning an error, and when its dev looked at the logs he saw that the request on his end was:
'campaign_id' => '4'
'photo_file' => '#/Users/andrew/Sites/roo/9699d27bb09fda3133701ca9af084e3d.jpg'
so adding # to the beginning of the file didn't actually send the contents of the file, like I understand it's supposed to. Also, the API works fine with other platforms that use it, so the problem is definitely on my end.

Categories