Max YO 6 роки тому
батько
коміт
47c24a12ef

+ 52 - 0
src/Lib/Auth/GoogleAuthenticator_lib.php

@@ -0,0 +1,52 @@
+<?php
+
+namespace KarmaFW\Lib\Auth;
+
+use \PHPGangsta_GoogleAuthenticator;
+
+
+class GoogleAuthenticator_lib
+{
+
+	public static function generateSecret($length=16)
+	{
+		$ga = new PHPGangsta_GoogleAuthenticator();
+		$secret = $ga->createSecret($length);
+		//echo "Secret is: ".$secret."\n\n";
+		return $secret;
+	}
+
+	public static function getQrCode($secret)
+	{
+		$ga = new PHPGangsta_GoogleAuthenticator();
+		
+		$qrCodeUrl = $ga->getQRCodeGoogleUrl(APP_NAME, $secret);
+		//echo "Google Charts URL for the QR-Code: " . $qrCodeUrl . "\n\n";
+
+		return $qrCodeUrl;
+	}
+
+	public static function checkCode($secret, $entered_code) 
+	{
+		$ga = new PHPGangsta_GoogleAuthenticator();
+		
+		/*
+		$oneCode = $ga->getCode($secret);
+		echo "Checking Code '$oneCode' and Secret '$secret':\n";
+
+		if ($entered_code != $oneCode) {
+			echo "Wrong code ($entered_code != $oneCode)";
+		}
+		*/
+
+		$checkResult = $ga->verifyCode($secret, $entered_code, 2);    // 2 = 2*30sec clock tolerance
+		if ($checkResult) {
+			//echo 'OK';
+		} else {
+			//echo 'FAILED';
+		}
+		return $checkResult;
+	}
+
+}
+

+ 232 - 0
src/Lib/Payment/Paypal_lib.php

@@ -0,0 +1,232 @@
+<?php
+
+namespace KarmaFW\Lib\Payment;
+
+use \PayPal;
+
+
+// SANDBOX DB valide => visa: 4556142984862862 / mastercard: 5583942466987606 / amex: 345343966611301
+// SANDBOX DB refusee => visa: 4111111111111111 / mastercard: 5555555555554444 / amex: 378282246310005
+
+
+class Paypal_lib
+{
+	// https://github.com/paypal/PayPal-PHP-SDK/wiki/Making-First-Call
+	// https://www.grafikart.fr/tutoriels/paypal-express-checkout-rest-962
+	
+	public static function PaymentPaypal($payment_label='', $payment_product_label='', $payment_price=0, $customer_description='')
+	{
+		// Paypal STEP 1 (creating payment)
+
+		if (empty($payment_price) || ! defined('PAYPAL_ENV')) {
+			return false;
+		}
+
+		if (PAYPAL_ENV == 'PROD') {
+			if (! defined('PAYPAL_PROD_CLIENT_ID') || ! defined('PAYPAL_PROD_SECRET')) {
+				return false;
+			}
+			$paypal_public_key = PAYPAL_PROD_CLIENT_ID;
+			$paypal_secret_key = PAYPAL_PROD_SECRET;
+
+		} else {
+			if (! defined('PAYPAL_SANDBOX_CLIENT_ID') || ! defined('PAYPAL_SANDBOX_SECRET')) {
+				return false;
+			}
+			$paypal_public_key = PAYPAL_SANDBOX_CLIENT_ID;
+			$paypal_secret_key = PAYPAL_SANDBOX_SECRET;
+		}
+
+
+
+		// Step 1 (auth)
+		$apiContext = new \PayPal\Rest\ApiContext(
+		        new \PayPal\Auth\OAuthTokenCredential(
+		            $paypal_public_key,     // ClientID
+		            $paypal_secret_key      // ClientSecret
+		        )
+		);
+
+		$apiContext->setConfig([
+			//'log.LogEnabled' => true,
+			//'log.FileName' => '/tmp/PayPal.log',
+			//'log.LogLevel' => 'FINE',
+			'mode' => (PAYPAL_ENV == 'PROD') ? 'live' : 'sandbox',
+		]);
+
+		
+
+		// (prepare data)
+		$payer = new \PayPal\Api\Payer();
+		$payer->setPaymentMethod('paypal');
+
+
+		$amount = new \PayPal\Api\Amount();
+		$amount->setTotal($payment_price);
+		$amount->setCurrency('EUR');
+
+
+        // Build transaction
+		$transaction = new \PayPal\Api\Transaction();
+		$transaction->setAmount($amount);
+		
+		if (! empty($payment_label)) {
+			$transaction->setDescription($payment_label); // optionnal
+		}
+
+		if (! empty($payment_product_label)) {
+			// specify products list
+			$list = new \PayPal\Api\ItemList();
+			$item = (new \PayPal\Api\Item())
+	                ->setName($payment_product_label)
+	                ->setPrice($payment_price)
+	                ->setCurrency('EUR')
+	                ->setQuantity(1);
+	        $list->addItem($item);
+			$transaction->setItemList($list); // optionnal
+		}
+
+		if (! empty($customer_description)) {
+			// specify a "custom" value for this customer (ex: user_id or user_email)
+			$transaction->setCustom($customer_description); // optionnal
+		}
+
+
+		// set redirections urls
+		$scheme = ( (! empty($_SERVER['REQUEST_SCHEME']) && $_SERVER['REQUEST_SCHEME'] == 'https') || (! empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (! empty($_SERVER['REDIRECT_HTTPS']) && $_SERVER['REDIRECT_HTTPS'] == 'on') ) ? 'https' : 'http';
+		$redirectUrls = new \PayPal\Api\RedirectUrls();
+		$redirectUrls->setReturnUrl($scheme."://" . $_SERVER['HTTP_HOST'] . "/paypal_callback")->setCancelUrl($scheme."://" . $_SERVER['HTTP_HOST'] . "/paypal_canceled");
+
+
+		// Build payment
+		$payment = new \PayPal\Api\Payment();
+		$payment->setIntent('sale')
+		    ->setPayer($payer)
+		    ->setTransactions(array($transaction))
+		    ->setRedirectUrls($redirectUrls);
+
+
+		// Create payment via API
+		$approval_url = null;
+		$paypal_error = '';
+		$paymentId = null;
+		try {
+		    $payment->create($apiContext);
+		    //echo "<pre>" . PHP_EOL . $payment . PHP_EOL . "</pre>" . PHP_EOL; exit;
+
+		    $approval_url = $payment->getApprovalLink();
+		    $paymentId = $payment->getId();
+		    //echo '\n\nRedirect user to approval_url: <a href="' . $approval_url . '">' . $approval_url . '</a>';
+		
+		} catch (\PayPal\Exception\PayPalConnectionException $e) {
+		    //echo "<pre>" . $e->getData() . "</pre>"; exit;
+		    $error_data = json_decode($e->getData());
+		    $paypal_error = $e->getMessage();
+		    if (! empty($error_data->error_description)) {
+		    	$paypal_error = $error_data->error_description;
+		    }
+		}
+
+
+		return [
+			'approval_url' => $approval_url,
+			'paypal_error' => $paypal_error,
+			'paymentId' => $paymentId,
+		];
+	}
+
+
+
+	public static function PaymentPaypal_Callback()
+	{
+		// Paypal STEP 2 (validating payment)
+
+		if (! defined('PAYPAL_ENV')) {
+			return false;
+		}
+
+		if (PAYPAL_ENV == 'PROD') {
+			if (! defined('PAYPAL_PROD_CLIENT_ID') || ! defined('PAYPAL_PROD_SECRET')) {
+				return false;
+			}
+			$paypal_public_key = PAYPAL_PROD_CLIENT_ID;
+			$paypal_secret_key = PAYPAL_PROD_SECRET;
+
+		} else {
+			if (! defined('PAYPAL_SANDBOX_CLIENT_ID') || ! defined('PAYPAL_SANDBOX_SECRET')) {
+				return false;
+			}
+			$paypal_public_key = PAYPAL_SANDBOX_CLIENT_ID;
+			$paypal_secret_key = PAYPAL_SANDBOX_SECRET;
+		}
+
+		$paypal_error = '';
+		$payment_ok = false;
+
+	    $paymentId = get('paymentId');
+	    $token = get('token');
+	    $PayerID = get('PayerID');
+
+	    if (empty($paymentId) || empty($token) || empty($PayerID)) {
+	    	$paypal_error = 'missing parameters';
+
+	    } else {
+			// Step 1 (auth)
+			$apiContext = new \PayPal\Rest\ApiContext(
+			        new \PayPal\Auth\OAuthTokenCredential(
+			            $paypal_public_key,     // ClientID
+			            $paypal_secret_key      // ClientSecret
+			        )
+			);
+
+			// Step 2
+	    	$payment = \PayPal\Api\Payment::get($paymentId, $apiContext);
+			$execution = (new \PayPal\Api\PaymentExecution())->setPayerId($PayerID);
+
+			try {
+			    $payment->execute($execution, $apiContext);
+			    //echo 'Merci pour votre paiement';
+			    $payment_ok = true;
+
+			} catch (\PayPal\Exception\PayPalConnectionException $e) {
+			    $error_data = json_decode($e->getData());
+			    //var_dump($error_data);
+			    $paypal_error = $e->getMessage();
+			    if (! empty($error_data->details[0]->issue)) {
+			    	$paypal_error = $error_data->details[0]->issue;
+			    }
+			}
+		}
+
+		$paypal_result = [
+			'payment_ok' => $payment_ok,
+	    	'paymentId' => $paymentId,
+	    	'token' => $token,
+	    	'PayerID' => $PayerID,
+	    	'payment' => $payment,
+		];
+
+		if (! $payment_ok) {
+			return $paypal_result;
+		}
+
+
+		if (false) {
+			$transaction = $paypal_result['payment']->getTransactions()[0];
+
+			echo "paymentId: " . $paymentId . "<hr />";
+			echo "Status: " . $paypal_result['payment']->getState() . "<hr />"; // expected: approved
+			echo "Intent: " . $paypal_result['payment']->getIntent() . "<hr />"; // expected:  sale
+			echo "Cart: " . $paypal_result['payment']->getCart() . "<hr />";
+			echo "Description: " . $transaction->description . "<hr />";
+			echo "Item: " . $transaction->item_list->getItems()[0]->name . "<hr />";
+			echo "TotalPrice: " . $transaction->amount->total . "<hr />";
+
+			echo "<pre>" . print_r($paypal_result['payment'], 1);
+		}
+
+		return $paypal_result;
+
+	}
+
+}

+ 104 - 0
src/Lib/Payment/Stripe_lib.php

@@ -0,0 +1,104 @@
+<?php
+
+namespace KarmaFW\Lib\Payment;
+
+use \Stripe\Stripe;
+
+
+class Stripe_lib
+{
+
+	public static function PaymentStripe($stripe_token, $customer_id=null, $payment_label='', $payment_price=0, $save_customer=false, $new_customer_email=null, $new_customer_description=null)
+	{
+		if (empty($payment_price) || ! defined('STRIPE_ENV')) {
+			return false;
+		}
+
+		// TEST CB valide  => visa: 4242 4242 4242 4242  /  mastercard: 5555 5555 5555 4444
+		// TEST CB refusée => visa: 4242 4242 4242 1214  /  mastercard: 5555 5555 5555 7777
+
+		if (STRIPE_ENV == 'LIVE') {
+			if (! defined('STRIPE_LIVE_PUBLIC_KEY') || ! defined('STRIPE_LIVE_SECRET_KEY')) {
+				return false;
+			}
+			$stripe_public_key = STRIPE_LIVE_PUBLIC_KEY;
+			$stripe_secret_key = STRIPE_LIVE_SECRET_KEY;
+
+		} else {
+			if (! defined('STRIPE_TEST_PUBLIC_KEY') || ! defined('STRIPE_TEST_SECRET_KEY')) {
+				return false;
+			}
+			$stripe_public_key = STRIPE_TEST_PUBLIC_KEY;
+			$stripe_secret_key = STRIPE_TEST_SECRET_KEY;
+		}	
+
+		$stripe_error = '';
+		$payment_ok = false;
+		\Stripe\Stripe::setApiKey($stripe_secret_key);
+
+		try {
+			if ($save_customer && empty($customer_id)) {
+				$customer = \Stripe\Customer::create([
+					'email' => $new_customer_email,
+					'description' => $new_customer_description,
+					'source'  => $stripe_token,
+				]);
+				$customer_id = $customer->id;
+			}
+
+
+			$charge_infos = [
+			    'amount' => $payment_price * 100, // en centimes
+			    'currency' => 'eur',
+			    'description' => $payment_label,
+			    //'source' => $stripe_token, // soit on utilise 'source' soit on utilise 'customer', mais pas les 2 en meme temps
+			    //'customer' => $customer_id,
+			];
+			if ($save_customer) {
+				$charge_infos['customer'] = $customer_id;
+
+			} else {
+				$charge_infos['source'] = $stripe_token;
+			}
+			$charge = \Stripe\Charge::create($charge_infos);
+			
+		} catch (\Stripe\Error\InvalidRequest $e) {
+			$charge = null;
+			$stripe_error = $e->getMessage();
+
+		} catch (\Stripe\Error\Card $e) {
+			$charge = null;
+			$stripe_error = $e->getMessage();
+		}
+
+
+		if (empty($charge)) {
+			// error: suite à une sortie en erreur du try/catch
+
+		}else if ($charge->status !== 'succeeded') {
+			// error: invalid charge status
+			$stripe_error = "statut de transaction invalide";
+
+		}else if ($charge->object !== 'charge') {
+			// error: invalid transaction type
+			$stripe_error = "type de transaction invalide";
+
+		}else if ($charge->amount != intval($payment_price * 100)) {
+			// error: invalid price
+			$stripe_error = "prix de transaction invalide";
+
+		} else {
+			// OK
+			$payment_ok = true;
+		}
+
+		return [
+			'payment_accepted' => $payment_ok,
+			'customer_id' => $customer_id,
+			'stripe_token' => $stripe_token,
+			'stripe_error' => $stripe_error,
+		];
+	}
+
+}
+

+ 38 - 0
src/Lib/Sms/SmsAuthenticator_lib.php

@@ -0,0 +1,38 @@
+<?php
+
+namespace KarmaFW\Lib\Auth;
+
+use KarmaFW\Lib\Sms\Sms_lib;
+
+
+class SmsAuthenticator_lib
+{
+
+	public static function sendSms($recipient, $message, $provider=null)
+	{
+		if ($provider == 'freemobile' || (defined('FREEMOBILE_PHONE_NUMBER' && FREEMOBILE_PHONE_NUMBER == $recipient))) {
+			if ($provider == 'freemobile' || (defined('FREEMOBILE_API_KEY') && FREEMOBILE_API_KEY != '' && defined('FREEMOBILE_API_SECRET') && FREEMOBILE_API_SECRET != '')) {
+				// Envoi via FreeMobile
+				return Sms_lib::sendSmsFreeMobile($message);
+			}
+		}
+
+		// Envoi via SmsEnvoi
+		return Sms_lib::sendSmsSmsEnvoi($recipient, $message, APP_NAME);
+
+		//return Sms_lib::sendSmsTwilio($recipient, $message);
+	}
+
+	public static function generateCode()
+	{
+		$code = rand(100000, 999999);
+		return $code;
+	}
+
+	public static function checkCode($entered_code) 
+	{
+		return ! empty($_SESSION['2fa']['code']) && $_SESSION['2fa']['code'] == $entered_code;
+	}
+
+}
+

+ 41 - 0
src/Lib/Sms/Sms_lib.php

@@ -81,6 +81,47 @@ class Sms_lib
 
 
 
+	/*
+	public static function sendSmsTwilio($numero, $message)
+	{
+		// https://www.twilio.com/docs/api/messaging/send-messages
+
+		if (! defined('TWILIO_API_KEY') || empty(TWILIO_API_KEY)) {
+			return false;
+		}
+		if (! defined('TWILIO_API_SECRET') || empty(TWILIO_API_SECRET)) {
+			return false;
+		}
+		
+		$url = "https://api.twilio.com/2010-04-01/Accounts/" . TWILIO_API_KEY . "/Messages.json";
+
+		$params = array(
+			"To" => urlencode($numero),
+			//"From" => urlencode("+33682437831"),
+			"From" => urlencode("+33644646493"),
+			"Body" => urlencode($message),
+			//"MediaUrl" => "http://www.example.com/cheeseburger.png",
+		);
+		$postdata = http_build_query($params);
+
+		$opts = array(
+			'http' => array(
+		        'method'  => 'POST',
+		        'header'  => "Content-type: application/x-www-form-urlencoded\r\n" . "Authorization: Basic " . base64_encode(TWILIO_API_KEY . ":" . TWILIO_API_SECRET),
+		        'content' => $postdata
+	    	)
+		);
+		//print_r($opts);
+		$context = stream_context_create($opts);
+
+		// NE FONCTIONNE PAS => HTTP/1.1 400 BAD REQUEST  => A DEBUGER
+
+		//echo $url; exit;
+		$result = file_get_contents($url, false, $context);
+		echo $result; exit;
+	}
+	*/
+	
 }
 
 

+ 23 - 0
src/Lib/Url/Bitly_lib.php

@@ -0,0 +1,23 @@
+<?php
+
+namespace KarmaFW\Lib\Url;
+
+
+class Bitly_lib
+{
+
+	public static function getBitlyShortUrl($long_url) {
+
+		if (! defined('BITLY_USERNAME') || empty(BITLY_USERNAME)) {
+			return false;
+		}
+		if (! defined('BITLY_APIKEY') || empty(BITLY_APIKEY)) {
+			return false;
+		}
+		
+		$result = file_get_contents("http://api.bit.ly/v3/shorten?login=" . BITLY_USERNAME . "&apiKey=" . BITLY_APIKEY . "&longUrl=".urlencode($long_url)."&format=json");
+		$short_url = json_decode($result)->data->url;
+		return $short_url;
+	}
+
+}