how to Use Blockchain receive api without exchange rate? - php

i have integrated blockchain recieve api for blockchain payment gateway. but when i go to pay enter amount to add balance it converts that amount into usd
i want to receive directly in BTC not in usd . when i remove below URL from my coding it gives error please help
if ($sendto!="") {
$api = "https://blockchain.info/tobtc?currency=USD&value=".$data['amount'];
$usd = file_get_contents($api );
$tran->btc_amo = $usd;
$tran->btc_acc = $sendto;
$tran->save();

I read their documentation and they don't have USD to BTC. But, if you need USD to BTC. You can try it yourself like the following
$one_usd_in_btc = https://blockchain.info/tobtc?currency=USD&value=1
$usd_to_btc = $one_usd_in_btc * your_usd

If you want the inverse:
NOT USD to BTC from the API
BUT BTC to USD then you need the inverse.
Original formula
const bitcoinrate;
function usd_to_btc($usd) {
$btc = $usd * bitcoinrate;
}
The opposite
function btc_to_usd($btc) {
$usd = $btc / bitcoinrate;
}
But your code already contains the amount in USD in the first place. $data['amount']

Related

API/SDK Checkout.com - Set Phone and Shipping Address to a payment

I'm using Checkout.com and its PHP SDK to set up payment on a website.
I try to set the Phone and The Shipping Address, but i'm doing wrong i suppose.
The API is not so amazing about this as well (or i don't know how to use it to find what i want)
I did something like this for the phone but doesn't work
$customerPhone = new \Checkout\Models\Phone();
$customerPhone->number = $phone;
$payment->shipping = new \stdClass();
$payment->shipping->phone = $customerPhone;
And i have no idea for the address.
If someone knows ?
Thanks
The correct way of sending shipping data on payments is:
$shipping = new \Checkout\Models\Payments\Shipping($address, $phone);
Where $address is an object of Checkout\Models\Address and $phone is an object of Checkout\Models\Phone.

Is there any better way to get Currency Exchange Rate in PHP?

Currency Exchange Rate with below code is working sometimes and not working sometimes and not at all reliable. Is there any better way to get Currency Exchange Rate in PHP?
public function getJPYtoUSDExchangeRate(){
$from = 'JPY';
$to = 'USD';
$amount = 1;
$data = file_get_contents("https://finance.google.com/finance/converter?a=$amount&from=$from&to=$to");
preg_match("/<span class=bld>(.*)<\/span>/",$data, $converted);
$converted = preg_replace("/[^0-9.]/", "", $converted[1][0]);
return number_format(round($converted, 3),2);
}
You have several issues:
You're not calling an actual API, you're scraping a web page, which means that:
you're most likely violating Google's TOS
you're more likely to get rate-limited (or be detected as abuse and blacklisted) at some point if you're fetching this page too often
you're dependent on any change made in the HTML structure of the web page
You're scraping the page every single time you need to convert an amount to another currency, which means that any failure makes your currency conversion fail.
What you should do:
load exchange rates from a legitimate feed or API
load them on a regular basis (via a cron job for example) and save them to a local database, that will be used to perform currency conversions
This way, even if an API call fails, you still have access to a slightly outdated exchange rate, which is better than a failure in most cases.
Where do you find a trustable exchange rate feed?
There are plenty of APIs, free or not, that offer this service.
A good source I know of is the European Central Bank, who provides an XML feed that's been there for years and provides exchange rates for 32 currencies relative to EUR.
OpenExchangeRates also offers a free plan with a limit of 1,000 requests per month, which is enough to refresh rates every hour. It provides exchange rates for 170 currencies, relative to USD.
How do you store the values in your database?
Whichever feed you choose, you need to parse it (if XML) or json_decode() it (if JSON) and store the values in your database. Ideally, set up a cron job to run your import script daily or even hourly.
The actual parsing and importing steps are outside the scope of this question, but let's assume a simple MySQL table that holds the records:
CREATE TABLE exchange_rate(
target_currency CHAR(3) COLLATE ascii_bin NOT NULL PRIMARY KEY,
exchange_rate DOUBLE NOT NULL
);
How to properly handle currency conversions based on rates relative to a single currency?
This is a question I've answered recently. The feeds above give you rates to convert the base currency (EUR or USD) to another currency, but do not give you a clue on how to convert between two arbitrary currencies. I would suggest you use a proper library that handles these conversions for you, such as brick/money - disclaimer: I'm the author.
Here is how you would configure it to load your exchange rates from the table above:
use Brick\Money\CurrencyConverter;
use Brick\Money\ExchangeRateProvider\PDOProvider;
use Brick\Money\ExchangeRateProvider\PDOProviderConfiguration;
use Brick\Money\ExchangeRateProvider\BaseCurrencyProvider;
// set to whatever your rates are relative to
$baseCurrency = 'USD';
// use your own credentials, or re-use your existing PDO connection
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$configuration = new PDOProviderConfiguration();
$configuration->tableName = 'exchange_rate';
$configuration->exchangeRateColumnName = 'exchange_rate';
$configuration->targetCurrencyColumnName = 'target_currency';
$configuration->sourceCurrencyCode = $baseCurrency;
// this provider loads exchange rates from your database
$provider = new PDOProvider($pdo, $configuration);
// this provider calculates exchange rates relative to the base currency
$provider = new BaseCurrencyProvider($provider, $baseCurrency);
// this currency converter can now handle any currency pair
$converter = new CurrencyConverter($provider);
And how you would use it:
use Brick\Math\RoundingMode;
use Brick\Money\Money;
$money = Money::of(10, 'EUR'); // EUR 10.00
$converter->convert($money, 'CAD', RoundingMode::DOWN); // CAD 15.27
CurrencyFreaks API provides trusty exchange rates for 179 currencies worldwide in JSON and XML formats compatible with multiple programming languages. By using CurrencyFreaks API, you can also change the 'base' currency and can get exchange rates for specific currencies.
Here is a simple currency exchange rate endpoint by using PHP:
setUrl('https://api.currencyfreaks.com/latest
?apikey=YOUR_APIKEY
&base=GBP');
$request->setMethod(HTTP_Request2::METHOD_GET);
$request->setConfig(array(
'follow_redirects' => TRUE
));
try {
$response = $request->send();
if ($response->getStatus() == 200) {
echo $response->getBody();
}
else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
}
catch(HTTP_Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
The JSON response will be:
{
"date": "2020-10-06 11:22:00+00",
"base": "GBP",
"rates": {
"FJD": "2.737385252915371",
"MXN": "27.74546375788785",
"STD": "27185.017172962733",
"LVL": "0.8482572402792966",
"SCR": "23.257414775003944",
"CDF": "2535.4260357935937",
"BBD": "2.585121591194042",
"GTQ": "10.055244048403818",
"CLP": "1031.8523300993463",
"HNL": "31.82062875327341",
"UGX": "4769.159332676713",
"ZAR": "21.445845580346873",
"TND": "3.542262860333636",
"CUC": "1.2926654930214643",
"BSD": "1.292560795597021",
"SLL": "12676.789824444395",
"SDG": "71.5109260164052",
"IQD": "1542.8992384231794",
"GMD": "66.89002117214584",
"CUP": "34.25286108332106",
"TWD": "37.17921872455271",
"RSD": "128.99756740058268",
"DOP": "75.46618143934401",
"KMF": "540.1610026652604",
.
.
.
[179 Currencies]
}
}
I hope it works.
The bank of Canada provides RSS feed for these currencies :
AUD, BRL, CNY, EUR, HKD, INR, IDR, JPY, MXN, NZD, NOK, PEN, RUB, SAR, SGD, ZAR, KRW, SEK, CHF, TWD, TRY, GBP, USD
Here is a way of getting currency conversions without API or 3rd party service:
<?php
class EXCHANGE {
public $Rates;
public $Rate;
public function __construct(){
$this->Rates = $this->fetchAllRates();
foreach($this->Rates as $currency => $rate){
$this->Rate[$currency] = $rate['latest'];
}
}
public function fetchAllRates(){
$currencies = ["AUD","BRL","CNY","EUR","HKD","INR","IDR","JPY","MXN","NZD","NOK","PEN","RUB","SAR","SGD","ZAR","KRW","SEK","CHF","TWD","TRY","GBP","USD"];
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, "https://www.bankofcanada.ca/valet/observations/group/FX_RATES_DAILY/json?start_date=2010-01-01");
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, 1);
$rates = curl_exec($cURL);
curl_close($cURL);
$rates = json_decode($rates,true)['observations'];
foreach($currencies as $currency){
foreach($rates as $rate){
$AllRates[$currency][$rate['d']] = $rate['FX'.$currency.'CAD']['v'];
$AllRates[$currency]['latest'] = $rate['FX'.$currency.'CAD']['v'];
}
}
return $AllRates;
}
public function convert($value,$from,$to){
if($to == "CAD"){ return $value*$this->Rate[$from]; }
else { return ($value*$this->Rate[$from])/$this->Rate[$to]; }
}
}
$Exchange = new EXCHANGE();
foreach($Exchange->Rate as $currency => $rate){
echo $currency.': '.$rate."<br>\n"; // Listing all the exchange rates
}
echo "Converting 2.00 USD to CAD : ".$Exchange->convert(2,"USD","CAD")."\n"; //2022-02-23 = 2.5486
echo "Converting 2.00 USD to AUD : ".$Exchange->convert(2,"USD","AUD")."\n"; //2022-02-23 = 2.7708197434225
Update:
I had initially forgot to put the convert method.
Information:
This class is using the RSS feed of the Bank of Canada. It is not the most accurate data, because it is only updated once per business day. The $Rate property contains the exchange rates for CAD currency. Thus to convert other currencies, it first converts the initial currency to CAD and then to the new currency. So in the example provided above, 2.00 USD is converted to 2.5486 CAD. Then divided by the exchange rate of AUD resulting in 2.7708197434225 AUD.

WordPress: Store stripe info as user_meta

I'm using a Stripe webhook to store the dollar amount a customer is charged when they get charged in Stripe.
I've got the webhook working fine and can email out the charge amount but can't seem to store it in WordPress user_meta field.
Here's what my code looks like:
// Retrieve the request's body and parse it as JSON
$input = #file_get_contents("php://input");
$event_json = json_decode($input);
// Check against Stripe to confirm that the ID is valid
$event = \Stripe\Event::retrieve($event_json->id);
// If charge is successful, store in user meta
if (isset($event) && $event->type == "charge.succeeded") {
$amount = $event->data->object->amount / 100;
}
$payment_user_id = 9192321;
update_user_meta($payment_user_id, 'payment_history', $amount);
Is this because the json received from stripe is in a format that needs to be converted to something before I can store it? If I try to convert it to an integer using intval($amount) it just stores it as 0.
Thanks in advance!
Turns out I'm dumb and just needed to put the "update_user_meta" in the "if" statement.

Get invoice after payment paypal for merchant api php

My problem is that I want to get a bill after paying for storage ( in .pdf) on the server. I've been looking at the API and create an invoice but know not how to get the bill automatically.
<?php
require __DIR__ . '/../bootstrap.php';
use PayPal\Api\Address;
use PayPal\Api\BillingInfo;
use PayPal\Api\Cost;
use PayPal\Api\Currency;
use PayPal\Api\Invoice;
use PayPal\Api\InvoiceAddress;
use PayPal\Api\InvoiceItem;
use PayPal\Api\MerchantInfo;
use PayPal\Api\PaymentTerm;
use PayPal\Api\Phone;
use PayPal\Api\ShippingInfo;
$invoice = new Invoice();
Invoice Info
$invoice
->setMerchantInfo(new MerchantInfo())
->setBillingInfo(array(new BillingInfo()))
->setNote("Medical Invoice 16 Jul, 2013 PST")
->setPaymentTerm(new PaymentTerm())
->setShippingInfo(new ShippingInfo());
Merchant Info
A resource representing merchant information that can be used to identify merchant
$invoice->getMerchantInfo()
->setEmail("jaypatel512-facilitator#hotmail.com")
->setFirstName("Dennis")
->setLastName("Doctor")
->setbusinessName("Medical Professionals, LLC")
->setPhone(new Phone())
->setAddress(new Address());
$invoice->getMerchantInfo()->getPhone()
->setCountryCode("001")
->setNationalNumber("5032141716");
Address Information
The address used for creating the invoice
$invoice->getMerchantInfo()->getAddress()
->setLine1("1234 Main St.")
->setCity("Portland")
->setState("OR")
->setPostalCode("97217")
->setCountryCode("US");
Billing Information
Set the email address for each billing
$billing = $invoice->getBillingInfo();
$billing[0]
->setEmail("example#example.com");
$billing[0]->setBusinessName("Jay Inc")
->setAdditionalInfo("This is the billing Info")
->setAddress(new InvoiceAddress());
$billing[0]->getAddress()
->setLine1("1234 Main St.")
->setCity("Portland")
->setState("OR")
->setPostalCode("97217")
->setCountryCode("US");
Items List
You could provide the list of all items for detailed breakdown of invoice
$items = array();
$items[0] = new InvoiceItem();
$items[0]
->setName("Sutures")
->setQuantity(100)
->setUnitPrice(new Currency());
$items[0]->getUnitPrice()
->setCurrency("USD")
->setValue(5);
Tax Item
You could provide Tax information to each item.
$tax = new \PayPal\Api\Tax();
$tax->setPercent(1)->setName("Local Tax on Sutures");
$items[0]->setTax($tax);
Second Item
$items[1] = new InvoiceItem();
Lets add some discount to this item.
$item1discount = new Cost();
$item1discount->setPercent("3");
$items[1]
->setName("Injection")
->setQuantity(5)
->setDiscount($item1discount)
->setUnitPrice(new Currency());
$items[1]->getUnitPrice()
->setCurrency("USD")
->setValue(5);
Tax Item
You could provide Tax information to each item.
$tax2 = new \PayPal\Api\Tax();
$tax2->setPercent(3)->setName("Local Tax on Injection");
$items[1]->setTax($tax2);
$invoice->setItems($items);
Final Discount
You can add final discount to the invoice as shown below. You could either use "percent" or "value" when providing the discount
$cost = new Cost();
$cost->setPercent("2");
$invoice->setDiscount($cost);
$invoice->getPaymentTerm()
->setTermType("NET_45");
Shipping Information
$invoice->getShippingInfo()
->setFirstName("Sally")
->setLastName("Patient")
->setBusinessName("Not applicable")
->setPhone(new Phone())
->setAddress(new InvoiceAddress());
$invoice->getShippingInfo()->getPhone()
->setCountryCode("001")
->setNationalNumber("5039871234");
$invoice->getShippingInfo()->getAddress()
->setLine1("1234 Main St.")
->setCity("Portland")
->setState("OR")
->setPostalCode("97217")
->setCountryCode("US");
Logo
You can set the logo in the invoice by providing the external URL pointing to a logo
$invoice->setLogoUrl('https://www.paypalobjects.com/webstatic/i/logo/rebrand/ppcom.svg');
For Sample Purposes Only.
$request = clone $invoice;
try {
Create Invoice
Create an invoice by calling the invoice->create() method with a valid ApiContext (See bootstrap.php for more on ApiContext)
$invoice->create($apiContext);
} catch (Exception $ex) {
NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
ResultPrinter::printError("Create Invoice", "Invoice", null, $request, $ex);
exit(1);
}
NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
ResultPrinter::printResult("Create Invoice", "Invoice", $invoice->getId(), $request, $invoice);
return $invoice;
if they could orient themselves, or some link which explains how to find it I would be grateful

Authorize.net AIM Transaction

require_once 'anet_php_sdk/AuthorizeNet.php';
define("AUTHORIZENET_API_LOGIN_ID", $authLogin);
define("AUTHORIZENET_TRANSACTION_KEY", $authKey);
//Set to true for test account, set to false for real account
define("AUTHORIZENET_SANDBOX", true);
$sale = new AuthorizeNetAIM;
$sale->amount = $contractorRate;
$sale->card_num = $ccnumber;
$sale->exp_date = $ccexpire;
$sale->card_code = $cccvv;
$response = $sale->authorizeAndCapture();
//If approved, use this for getting the transaction ID.
if ($response->approved) {
$transaction_id = $response->transaction_id;
//ARB creates the subscription and sets the start date 30 days from the time of submission.
require_once 'anet_php_sdk/AuthorizeNet.php';
define("AUTHORIZENET_API_LOGIN_ID", $authLogin);
define("AUTHORIZENET_TRANSACTION_KEY", $authKey);
$subscription = new AuthorizeNet_Subscription;
$subscription->name = "PumpSpy Monitoring";
$subscription->intervalLength = "1";
$subscription->intervalUnit = "months";
$subscription->startDate = $subStartDate;
$subscription->totalOccurrences = "9999";
$subscription->amount = $contractorRate;
$subscription->creditCardCardNumber = $ccnumber;
$subscription->creditCardExpirationDate= $ccexpire;
$subscription->creditCardCardCode = $cccvv;
$subscription->billToFirstName = $firstname;
$subscription->billToLastName = $lastname;
// Create the subscription.
$request = new AuthorizeNetARB;
$response = $request->createSubscription($subscription);
Above is my code for validating the credit card (using AIM) and creating the subscription 30 days later (using ARB). The issue I'm having is trying to use 0.00 for the AIM sale amount. It's not accepting anything, even if I change the sale to AUTH_ONLY.
I think Visa requires an address and zip code? Is there something I'm missing with the required values with AIM to charge 0.00?
Note: This code works as long as $contractorRate has a value above 0 - which is fine, but if the contractor wants to wait 30 days to charge the customer, I don't want to charge them with AIM at first.
The merchant account provider probably does not support $0.00 amounts. You should content them to verify they do. If they don't you can do an authorization for $0.01 and then void the transaction afterwards.
Address and zip code is not required to process a transaction but is required to perform AVS. Failure to perform AVS can result in a transaction being charged the maximum rate applicable.

Categories