Pull Payments details from Stripe API - php

I am creating a WordPress plugin, and trying to pull payments details from stripe API done via third party. I have tried everything mention in this code but I am not able to pull data of Payments from stripe.
I need to fetch payment details from stripe API
https://stripe.com/docs/api/transfers?lang=php
I have tried payouts \Stripe\Payout::all() but getting empty object
Here is my code:
namespace wpmember;
class WPMember
{
public function __construct()
{
add_action( 'admin_menu', array($this, 'wpdocs_register_my_custom_menu_page') );
}
public function wpdocs_register_my_custom_menu_page()
{
add_menu_page(
'Custom Menu Title',
'custom menu',
'manage_options',
'custom-menu',
$this->connect_stripe()
);
}
public function connect_stripe()
{
require ( PLUGIN_DIR . 'vendor/autoload.php');
//echo PLUGIN_DIR . 'vendor/autoload.php';
\Stripe\Stripe::setApiKey("xxxx");
\Stripe\Stripe::setApiKey("xxxx");
$customers = \Stripe\Customer::all(["limit" => 3]);
$products = \Stripe\Product::all(["limit" => 3]);
$subscriptions = \Stripe\Subscription::all(['limit'=>3]);
$orders = \Stripe\Order::all(["limit" => 3]);
$allpayouts = \Stripe\Payout::all(["limit" => 3]);
$paymentIntent = \Stripe\PaymentIntent::all(["limit" => 3]);
//$payout = \Stripe\Payout::retrieve($allpayouts->data[0]->id);
$invoice = \Stripe\Invoice::all(["limit" => 3]);
echo "<pre>";
print_r($subscriptions);
echo "</pre>";
}
}

You seem to be fetching Payouts which are according to the Stripe API reference are the transfers from your Stripe account to your bank account. Which do not seem to be Charges object you showed on your screenshot or Transfer objects that could be fetched with \Stripe\Transfer::all().

Here you can get the payment details:
require ( PLUGIN_DIR . 'vendor/autoload.php');
\Stripe\Stripe::setApiKey("pk_test_VNbKcUGTqFIlyfIwFgizNx8h");
\Stripe\Stripe::setApiKey("sk_test_7VbuCbiZsDZjDHHlOtHeCqo7");
$charges = \Stripe\Charge::all(["limit" => 3]);
print_r($charges);

Related

How to get BACS account details in Woocommerce using API?

I already done with https://acp.sample.ph/wc/v3/order created in PHP but the response of the API doesn't show the bank/account details for Bank account transfer (BACS). I am using the package automattic/woocommerce for fetching the API. This API I fetch is from WordPress woocommerce. Here's my sample code below.
$woocommerce = new Client(
'https://acp.sample.ph',
$credential['key'],
$credential['secrete'],
[
'wp_api' => true,
'version' => 'wc/v3',
'query_string_auth' => true
]
);
$data = array(
"order_id"=>"717",
"payment_method"=>"bacs"
);
$accounts = $woocommerce->post('process_payment', $data);
echo '<pre>';
print_r($accounts);
echo '</pre>';
You might need to create own endpoint or alter the Order API response
Can you try this ---
function prefix_wc_rest_prepare_order_object( $response, $object, $request ) {
// Get the value
$bacs_info = get_option( 'woocommerce_bacs_accounts');
$response->data['bacs_info'] = $bacs_info;
return $response;
}
add_filter( 'woocommerce_rest_prepare_shop_order_object', 'prefix_wc_rest_prepare_order_object', 10, 3 );

How to initialize a POST and a PUT method from inside a Wordpress custom endpoint

I am creating a custom endpoint in wordpress, which should do the following:
1. Create the path (done)
2. call a function, which:
2.1. Gets all the products from WooCommerce and stores them in an array (done)
2.2. Compares the products on WooCommerce with products from an external database and if there is any difference in data, get updated (PUT) by the data from the external DB
2.3. If some products exist on the external DB but do not exist on WooCommerce, create them on WooCommerce (POST)
I have managed to get all the data from WooCommerce via wc_get_products ($args) but I cannot find how to write the PUT and the POST method to update or create products.
If I use Automatic/WooCommerce to push or put products from a standalone file (not from the custom endpoint) works, but if I keep the Automatic/WooCommerce on the custom endpoint it tells me the following:
Failed to connect to localhost port 8000: Connection refused in /var/www/html/wp-content/plugins/wl-api/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php on line 417
which makes total sense because from the custom endpoint I am already connected to WooCommerce and the Automatic/WooCommerce would attempt to connect again. So are there any methods like wc_get_products but for PUT and PUSH?
//CUSTOM ENDPOINT PHP FILE
add_action('rest_api_init', 'customEndpoint');
function customEndpoint() {
register_rest_route('endpoint', '/transfer', array(
'methods' => 'GET',
'callback' => 'get_data',
));
}
function get_data() {
include "updateOrCreate.php";
}
//updateOrCreate.php
require 'vendor/autoload.php';
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require 'vendor/guzzlehttp/guzzle/src/Client.php';
use Automattic\WooCommerce;
//-----------Connect to the External DB----------
$baseUrl=...;
$externalClient = new GuzzleHttp\Client();
$res = $externalClient->request('GET', $baseUrl, [
"query" => ['fields' => $fields, 'aktiv' => true],
'auth' => ['...', '...']
]);
$articles = json_decode($res->getBody());
//-----------Connect to WooCommerce DB
$wooKey= "...";
$wooSecret= "...";
$wooCommerceBaseUrl = "http://localhost:8000";
$wooCommerceClient = new WooCommerce\Client($wooCommerceBaseUrl,
$wooKey, $wooSecret,
[
'wp_api' => true,
'version' => 'wc/v3',
]
);
//GET all products from WooCommerce
$args = array(
'status' => 'publish',
'limit' => -1,
);
$wooExistingProducts = wc_get_products($args);
$productsForWoo= [];
//check if there are no products on woocommerce:
if(empty($wooExistingProducts)){
foreach ($articles as &$article){
//Create the necessary template to initialize the connections between external products and woocommerce product template
$wooTemplate = [
...
];
array_push($productsForWoo, $wooTemplate);
//CREATE BATCHES OF 10
if(sizeof($productsForWoo) == 10){
$data = [
'create' => $productsForWoo,
];
$wooCommerceClient->post('products/batch', $data);
$productsForWoo = [];
}
}
//As there is a big chance that the last batch will have less than 10 products, push them as well to wooCommerce as a last batch
$data = [
'create' => $productsForWoo,
];
$wooCommerceClient->post('products/batch', $data);
}
// if there are existing products on woocommerce
else{
//Loop through all existing products on the external DB
foreach ($articles as &$article){
$did_match = false;
$wooTemplate = [
...
];
//loop through all products on WooCommerce
foreach ($wooExistingProducts as &$product){
//if the product id from the external db matches the id from an existing product on woocommerce
if(...){
//update that product
$wooCommerceClient->put('products/'.urlencode($product->id), $wooTemplate);
$did_match = true;
break;
}
}
//otherwise, if the product from the external db is not found on the woocommerce database, create it
if(!$did_match){
array_push($productsForWoo, $wooTemplate);
if(sizeof($productsForWoo) == 10){
$data = [
'create' => $productsForWoo,
];
$wooCommerceClient->post('products/batch', $data);
$productsForWoo = [];
}
}
}
//As there is a big chance that the last batch will have less than 10 products, push them as well to wooCommerce as a last batch
$data = [
'create' => $productsForWoo,
];
$wooCommerceClient->post('products/batch', $data);
}
I will deeply appreciate any input related to my issue. Thank you!
To get POST and PUT, you'll need to implement the methods (verbs).
You can use:
$verb = $_SERVER['REQUEST_METHOD'];
echo $verb;
... to test what HTTP request method (PUT vs GET) you're using.
Here's a SO article regarding PHP methods which I have bookmarked and often use when troubleshooting this. The code provided there is pretty clean and a great place to start.

Extending the woocommerce rest api

I would like to extend the woocommerce rest api to include data of its 'booking' extension plugin. Currently this extension does not have default endpoints provided by the rest api.
So far I have created a plugin, and I've added the following code;
add_filter( 'woocommerce_rest_prepare_product', 'custom_data');
function custom_data($response, $object) {
if( empty( $response->data ) )
return $response;
$response->data['meta_data'] = get_post_meta( $object[ID], 'availability', true);
return $response;
}
When I call the end point /products only the default data outlined by woocommerce is still called my little add on is no where to be found.
I don't even know where to find the above filter as I just saw this posted on a webpage and I tried to get it to do what I wanted, don't know if this is the correct direction to go down either. Webpage: https://francescocarlucci.com/woocommerce/woocommerce-api-custom-data-default-endpoints/#more-96
The above was me trying to extend the api but I also decided to try making a custom endpoint to see if I can get my desired outcome but so far I've just made a endpoint which calls but I have no idea what to write to retrieve the data I want.
custom end point code:
function register_custom_route() {
register_rest_route( 'ce/v1', '/bookable',
array(
'methods' => 'GET',
'callback' => 'get_bookable'
)
);
}
function get_bookable( ) {
return array( 'custom' => 'woocommerce here' );
//What code do I write here :(
}
Is there anyway I can achieve what I want under one of the above methods?
I'm quite new to dev and I'm familiar with javascript not PHP hence my need to want to use the rest api as I would like to use wordpress/woocommerce as a headless cms.
So far the closets example I've come to has been shown on this question Creating WooCommerce Custom API
Alternatively you can try the below code to extend product response of WooCommerce REST API without doing additionally, as your above hook "woocommerce_rest_prepare_product" is for v1 but currently it was v3 so the hook for the latest is below one(the below hook is from v2 controller of rest api which is extended by v3).
add_filter('woocommerce_rest_prepare_product_object', 'so54387226_custom_data', 10, 3);
function so54387226_custom_data($response, $object, $request) {
if (empty($response->data))
return $response;
$id = $object->get_id(); //it will fetch product id
$response->data['booking_meta_data'] = get_post_meta($id, 'availability', true);
return $response;
}
I tested the above code it works perfectly fine. Hope it may helps to someone who search for similar solution.
this is only part of my code. some variable not defined. and this just concept. hopefully, you can modify as per your requirement.
public function __construct() {
$this->template_url = apply_filters( 'woocommerce_template_url', 'woocommerce/'
);
$this->api_namespace = 'wc/v';
$this->base = 'home';
$this->api_version = '2';
add_action( 'woocommerce_loaded', array( $this, 'register_hooks' ) );
}
$namespace = $this->api_namespace . $this->api_version;
register_rest_route(
$namespace, '/wclogin/',
array(
'methods' => 'GET',
'callback' => array( $this, 'wc_login'),
)
);
function wc_login($request){
$user = get_user_by('email', $request["email"]);
//bad email
if(!$user){
$error = new WP_Error();
$error->add('invalid', __('<strong>ERROR</strong>: Either the email or password you entered is invalid.'));
return $error;
}
else{ //check password
if(!wp_check_password($request["password"], $user->user_pass, $user->ID)){ //bad password
$error = new WP_Error();
$error->add('invalid', __('<strong>ERROR</strong>: Either the email or password you entered is invalid.'));
return $error;
}else{
return $user; //passed
}
}
}
Just an update for those that come to this question. Now, there is a rest api for the booking extension: https://docs.woocommerce.com/document/bookings-rest-api-reference/

Programmatically create sales order using quote with custom shipping method in Magento

I would like to create sales orders programmatically using quotes with my own custom shipping method, shipping price & title.
This is my custom shipping method model:
<?php
class Mycompany_Mymodule_Model_Carrier
extends Mage_Shipping_Model_Carrier_Abstract
implements Mage_Shipping_Model_Carrier_Interface
{
protected $_code = 'icw_shipping';
public function collectRates(Mage_Shipping_Model_Rate_Request $request)
{
if (!Mage::registry($this->_code)) {
return false;
}
$info = Mage::registry($this->_code);
$method = Mage::getModel('shipping/rate_result_method');
$method->setCarrier($this->_code);
$method->setMethod($this->_code);
$method->setCarrierTitle($info['shippingCarrier']);
$method->setMethodTitle($info['shippingTitle']);
$method->setPrice($info['shippingPrice']);
$method->setCost($info['shippingPrice']);
$result = Mage::getModel('shipping/rate_result');
$result->append($method);
Mage::unregister($this->_code);
return $result;
}
public function getAllowedMethods()
{
return array(
$this->_code => 'ICW Shipping',
);
}
}
I try to use it like this:
// Method to save sales order quote
private function saveSalesOrderQuote()
{
Mage::register($this->_settings['ShippingMethod'], array(
'shippingCarrier' => 'Custom',
'shippingTitle' => $this->_orderData->ShippingMethod,
'shippingPrice' => $this->_orderData->ShippingAmount
));
$this->_quote->getShippingAddress()->setShippingMethod(
$this->_settings['ShippingMethod']
);
$this->_quote->getShippingAddress()->setCollectShippingRates(
true
);
$this->_quote->getShippingAddress()->collectShippingRates();
$this->_quote->collectTotals();
$this->_quote->reserveOrderId();
$this->_quote->save();
}
But it does not appear to be working. When the order is created, everything is correct expect for the shipping method, title & price. This is what I see in the backend:
Here's my full code so far: http://pastebin.com/jUTM0VbD
Any idea what I am doing wrong here? How do I use my own custom shipping method and set custom price and title?
Its very simple to add shipping method for order generated programmatically,
Follow above steps
$shippingAddress =$_quote->getShippingAddress()->addData($ShippingAddress);
$shippingAddress->setShippingMethod('methodname_methodname')->setCollectShippingRates(true)->collectShippingRates()->setPaymentMethod('methodcode'); //

Laravel/Omnipay paypal, pass custom shipping amount

I'm trying pass a custom shipping price to paypal express checkout.
I'm using omnipay and laravel 4.
I gather this is possible as referenced in the paypal express docs but cant get it to work with omnipay Ive tried the following:
/*set api details*/
$request = $gateway->purchase([
'amount'=> $cart['total'],
'currency' => 'GBP',
'XXX' => 100
'transactionId' => $order->reference,
'returnUrl' => $returnURL . '/checkout/success',
'cancelUrl' => $returnURL . '/checkout/cancel'
])->setItems($cart['items'])->send();
/*handleResponse*/
where XXX is shipping, shippingAmt, shipping_amount, I've tried adding shipping value to each item in the cart. I've tried modifying abstractrequest.php class to add on a shipping value manually like so:
protected function getItemData()
{
$data = array();
$items = $this->getItems();
if ($items) {
foreach ($items as $n => $item) {
$data["L_PAYMENTREQUEST_0_NAME$n"] = $item->getName();
$data["L_PAYMENTREQUEST_0_DESC$n"] = $item->getDescription();
$data["L_PAYMENTREQUEST_0_QTY$n"] = $item->getQuantity();
$data["L_PAYMENTREQUEST_0_AMT$n"] = $this->formatCurrency($item->getPrice());
}
}
$data["L_PAYMENTREQUEST_0_SHIPPINGAMT"] = "3.00";
return $data;
}
I found the answer here
I was using an older version of package, so just needed to run composer update and could use the function setShippingAmount();

Categories