File manager - Edit - /home/u816558632/domains/postills.com/public_html/public/unicodeveloper.tar
Back
laravel-paystack/.travis.yml 0000644 00000001055 15002141524 0012113 0 ustar 00 language: php php: - 7.3 install: travis_retry composer install --no-interaction --prefer-source script: - mkdir -p build/logs - vendor/bin/phpunit -c phpunit.xml.dist - vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover - vendor/bin/phpunit --coverage-clover build/logs/clover.xml after_script: - wget https://scrutinizer-ci.com/ocular.phar - php ocular.phar code-coverage:upload --format=php-clover coverage.clover - travis_retry php vendor/bin/coveralls -v notifications: slack: red-creek:5lI8ybvl6YTcCNPosh4TE13h laravel-paystack/.gitignore 0000644 00000000052 15002141524 0011766 0 ustar 00 build vendor .DS_Store composer.lock .idea laravel-paystack/CONTRIBUTING.md 0000644 00000002502 15002141524 0012231 0 ustar 00 # Contributing Contributions are **welcome** and will be fully **credited**. We accept contributions via Pull Requests on [Github](https://github.com/unicodeveloper/laravel-paystack). ## Pull Requests - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). - **Add tests!** - Your patch won't be accepted if it doesn't have tests. - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. - **Create feature branches** - Don't ask us to pull from your master branch. - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. ## Running Tests ``` bash $ composer test ``` **Happy coding**! laravel-paystack/composer.json 0000644 00000002507 15002141524 0012527 0 ustar 00 { "name": "unicodeveloper/laravel-paystack", "description": "A Laravel Package for Paystack", "keywords": [ "php", "github", "laravel", "Open Source", "payments", "subscription", "paystack", "paystack.co", "laravel 6", "laravel 7", "laravel 8" ], "license": "MIT", "authors": [ { "name": "unicodeveloper", "email": "prosperotemuyiwa@gmail.com" }, { "name": "iamfunsho", "email": "info@devfunsho.com" } ], "minimum-stability": "stable", "require": { "php": "^7.2|^8.0|^8.1", "illuminate/support": "~6|~7|~8|~9|^10.0", "guzzlehttp/guzzle": "~6|~7|~8|~9" }, "require-dev": { "phpunit/phpunit": "^8.4|^9.0", "scrutinizer/ocular": "~1.1", "php-coveralls/php-coveralls": "^2.0", "mockery/mockery": "^1.3" }, "autoload": { "files": [ "src/Support/helpers.php" ], "psr-4": { "Unicodeveloper\\Paystack\\": "src/" } }, "autoload-dev": { "psr-4": { "Unicodeveloper\\Paystack\\Test\\": "tests" } }, "scripts": { "test": "vendor/bin/phpunit" }, "extra": { "laravel": { "providers": [ "Unicodeveloper\\Paystack\\PaystackServiceProvider" ], "aliases": { "Paystack": "Unicodeveloper\\Paystack\\Facades\\Paystack" } } } } laravel-paystack/phpunit.xml.dist 0000644 00000001765 15002141524 0013165 0 ustar 00 <?xml version="1.0" encoding="UTF-8"?> <phpunit bootstrap="vendor/autoload.php" backupGlobals="false" backupStaticAttributes="false" colors="true" verbose="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false"> <testsuites> <testsuite name="laravel-paystack Test Suite"> <directory>tests</directory> </testsuite> </testsuites> <filter> <whitelist> <directory suffix=".php">src/</directory> </whitelist> </filter> <logging> <log type="tap" target="build/report.tap"/> <log type="junit" target="build/report.junit.xml"/> <log type="coverage-html" target="build/coverage" /> <log type="coverage-text" target="build/coverage.txt"/> <log type="coverage-clover" target="build/logs/clover.xml"/> </logging> </phpunit> laravel-paystack/resources/config/paystack.php 0000644 00000001324 15002141524 0015610 0 ustar 00 <?php /* * This file is part of the Laravel Paystack package. * * (c) Prosper Otemuyiwa <prosperotemuyiwa@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return [ /** * Public Key From Paystack Dashboard * */ 'publicKey' => getenv('PAYSTACK_PUBLIC_KEY'), /** * Secret Key From Paystack Dashboard * */ 'secretKey' => getenv('PAYSTACK_SECRET_KEY'), /** * Paystack Payment URL * */ 'paymentUrl' => getenv('PAYSTACK_PAYMENT_URL'), /** * Optional email address of the merchant * */ 'merchantEmail' => getenv('MERCHANT_EMAIL'), ]; laravel-paystack/README.md 0000644 00000033024 15002141524 0011262 0 ustar 00 # laravel-paystack [](https://packagist.org/packages/unicodeveloper/laravel-paystack) [](LICENSE.md) [](https://travis-ci.org/unicodeveloper/laravel-paystack) [](https://scrutinizer-ci.com/g/unicodeveloper/laravel-paystack) [](https://packagist.org/packages/unicodeveloper/laravel-paystack) > A Laravel Package for working with Paystack seamlessly ## Installation [PHP](https://php.net) 5.4+ or [HHVM](http://hhvm.com) 3.3+, and [Composer](https://getcomposer.org) are required. To get the latest version of Laravel Paystack, simply require it ```bash composer require unicodeveloper/laravel-paystack ``` Or add the following line to the require block of your `composer.json` file. ``` "unicodeveloper/laravel-paystack": "1.0.*" ``` You'll then need to run `composer install` or `composer update` to download it and have the autoloader updated. Once Laravel Paystack is installed, you need to register the service provider. Open up `config/app.php` and add the following to the `providers` key. ```php 'providers' => [ ... Unicodeveloper\Paystack\PaystackServiceProvider::class, ... ] ``` > If you use **Laravel >= 5.5** you can skip this step and go to [**`configuration`**](https://github.com/unicodeveloper/laravel-paystack#configuration) * `Unicodeveloper\Paystack\PaystackServiceProvider::class` Also, register the Facade like so: ```php 'aliases' => [ ... 'Paystack' => Unicodeveloper\Paystack\Facades\Paystack::class, ... ] ``` ## Configuration You can publish the configuration file using this command: ```bash php artisan vendor:publish --provider="Unicodeveloper\Paystack\PaystackServiceProvider" ``` A configuration-file named `paystack.php` with some sensible defaults will be placed in your `config` directory: ```php <?php return [ /** * Public Key From Paystack Dashboard * */ 'publicKey' => getenv('PAYSTACK_PUBLIC_KEY'), /** * Secret Key From Paystack Dashboard * */ 'secretKey' => getenv('PAYSTACK_SECRET_KEY'), /** * Paystack Payment URL * */ 'paymentUrl' => getenv('PAYSTACK_PAYMENT_URL'), /** * Optional email address of the merchant * */ 'merchantEmail' => getenv('MERCHANT_EMAIL'), ]; ``` ## General payment flow Though there are multiple ways to pay an order, most payment gateways expect you to follow the following flow in your checkout process: ### 1. The customer is redirected to the payment provider After the customer has gone through the checkout process and is ready to pay, the customer must be redirected to the site of the payment provider. The redirection is accomplished by submitting a form with some hidden fields. The form must send a POST request to the site of the payment provider. The hidden fields minimally specify the amount that must be paid, the order id and a hash. The hash is calculated using the hidden form fields and a non-public secret. The hash used by the payment provider to verify if the request is valid. ### 2. The customer pays on the site of the payment provider The customer arrives on the site of the payment provider and gets to choose a payment method. All steps necessary to pay the order are taken care of by the payment provider. ### 3. The customer gets redirected back to your site After having paid the order the customer is redirected back. In the redirection request to the shop-site some values are returned. The values are usually the order id, a payment result and a hash. The hash is calculated out of some of the fields returned and a secret non-public value. This hash is used to verify if the request is valid and comes from the payment provider. It is paramount that this hash is thoroughly checked. ## Usage Open your .env file and add your public key, secret key, merchant email and payment url like so: ```php PAYSTACK_PUBLIC_KEY=xxxxxxxxxxxxx PAYSTACK_SECRET_KEY=xxxxxxxxxxxxx PAYSTACK_PAYMENT_URL=https://api.paystack.co MERCHANT_EMAIL=unicodeveloper@gmail.com ``` *If you are using a hosting service like heroku, ensure to add the above details to your configuration variables.* Set up routes and controller methods like so: Note: Make sure you have `/payment/callback` registered in Paystack Dashboard [https://dashboard.paystack.co/#/settings/developer](https://dashboard.paystack.co/#/settings/developer) like so:  ```php // Laravel 5.1.17 and above Route::post('/pay', 'PaymentController@redirectToGateway')->name('pay'); ``` OR ```php Route::post('/pay', [ 'uses' => 'PaymentController@redirectToGateway', 'as' => 'pay' ]); ``` OR ```php // Laravel 8 & 9 Route::post('/pay', [App\Http\Controllers\PaymentController::class, 'redirectToGateway'])->name('pay'); ``` ```php Route::get('/payment/callback', 'PaymentController@handleGatewayCallback'); ``` OR ```php // Laravel 5.0 Route::get('payment/callback', [ 'uses' => 'PaymentController@handleGatewayCallback' ]); ``` OR ```php // Laravel 8 & 9 Route::get('/payment/callback', [App\Http\Controllers\PaymentController::class, 'handleGatewayCallback']); ``` ```php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Redirect; use Paystack; class PaymentController extends Controller { /** * Redirect the User to Paystack Payment Page * @return Url */ public function redirectToGateway() { try{ return Paystack::getAuthorizationUrl()->redirectNow(); }catch(\Exception $e) { return Redirect::back()->withMessage(['msg'=>'The paystack token has expired. Please refresh the page and try again.', 'type'=>'error']); } } /** * Obtain Paystack payment information * @return void */ public function handleGatewayCallback() { $paymentDetails = Paystack::getPaymentData(); dd($paymentDetails); // Now you have the payment details, // you can store the authorization_code in your db to allow for recurrent subscriptions // you can then redirect or do whatever you want } } ``` ```php /** * In the case where you need to pass the data from your * controller instead of a form * Make sure to send: * required: email, amount, reference, orderID(probably) * optionally: currency, description, metadata * e.g: * */ $data = array( "amount" => 700 * 100, "reference" => '4g4g5485g8545jg8gj', "email" => 'user@mail.com', "currency" => "NGN", "orderID" => 23456, ); return Paystack::getAuthorizationUrl($data)->redirectNow(); ``` Let me explain the fluent methods this package provides a bit here. ```php /** * This fluent method does all the dirty work of sending a POST request with the form data * to Paystack Api, then it gets the authorization Url and redirects the user to Paystack * Payment Page. We've abstracted all of it, so you don't have to worry about that. * Just eat your cookies while coding! */ Paystack::getAuthorizationUrl()->redirectNow(); /** * Alternatively, use the helper. */ paystack()->getAuthorizationUrl()->redirectNow(); /** * This fluent method does all the dirty work of verifying that the just concluded transaction was actually valid, * It verifies the transaction reference with Paystack Api and then grabs the data returned from Paystack. * In that data, we have a lot of good stuff, especially the `authorization_code` that you can save in your db * to allow for easy recurrent subscription. */ Paystack::getPaymentData(); /** * Alternatively, use the helper. */ paystack()->getPaymentData(); /** * This method gets all the customers that have performed transactions on your platform with Paystack * @returns array */ Paystack::getAllCustomers(); /** * Alternatively, use the helper. */ paystack()->getAllCustomers(); /** * This method gets all the plans that you have registered on Paystack * @returns array */ Paystack::getAllPlans(); /** * Alternatively, use the helper. */ paystack()->getAllPlans(); /** * This method gets all the transactions that have occurred * @returns array */ Paystack::getAllTransactions(); /** * Alternatively, use the helper. */ paystack()->getAllTransactions(); /** * This method generates a unique super secure cryptographic hash token to use as transaction reference * @returns string */ Paystack::genTranxRef(); /** * Alternatively, use the helper. */ paystack()->genTranxRef(); /** * This method creates a subaccount to be used for split payments * @return array */ Paystack::createSubAccount(); /** * Alternatively, use the helper. */ paystack()->createSubAccount(); /** * This method fetches the details of a subaccount * @return array */ Paystack::fetchSubAccount(); /** * Alternatively, use the helper. */ paystack()->fetchSubAccount(); /** * This method lists the subaccounts associated with your paystack account * @return array */ Paystack::listSubAccounts(); /** * Alternatively, use the helper. */ paystack()->listSubAccounts(); /** * This method Updates a subaccount to be used for split payments * @return array */ Paystack::updateSubAccount(); /** * Alternatively, use the helper. */ paystack()->updateSubAccount(); ``` A sample form will look like so: ```php <?php // more details https://paystack.com/docs/payments/multi-split-payments/#dynamic-splits $split = [ "type" => "percentage", "currency" => "KES", "subaccounts" => [ [ "subaccount" => "ACCT_li4p6kte2dolodo", "share" => 10 ], [ "subaccount" => "ACCT_li4p6kte2dolodo", "share" => 30 ], ], "bearer_type" => "all", "main_account_share" => 70 ]; ?> ``` ```html <form method="POST" action="{{ route('pay') }}" accept-charset="UTF-8" class="form-horizontal" role="form"> <div class="row" style="margin-bottom:40px;"> <div class="col-md-8 col-md-offset-2"> <p> <div> Lagos Eyo Print Tee Shirt ₦ 2,950 </div> </p> <input type="hidden" name="email" value="otemuyiwa@gmail.com"> {{-- required --}} <input type="hidden" name="orderID" value="345"> <input type="hidden" name="amount" value="800"> {{-- required in kobo --}} <input type="hidden" name="quantity" value="3"> <input type="hidden" name="currency" value="NGN"> <input type="hidden" name="metadata" value="{{ json_encode($array = ['key_name' => 'value',]) }}" > {{-- For other necessary things you want to add to your payload. it is optional though --}} <input type="hidden" name="reference" value="{{ Paystack::genTranxRef() }}"> {{-- required --}} <input type="hidden" name="split_code" value="SPL_EgunGUnBeCareful"> {{-- to support transaction split. more details https://paystack.com/docs/payments/multi-split-payments/#using-transaction-splits-with-payments --}} <input type="hidden" name="split" value="{{ json_encode($split) }}"> {{-- to support dynamic transaction split. More details https://paystack.com/docs/payments/multi-split-payments/#dynamic-splits --}} {{ csrf_field() }} {{-- works only when using laravel 5.1, 5.2 --}} <input type="hidden" name="_token" value="{{ csrf_token() }}"> {{-- employ this in place of csrf_field only in laravel 5.0 --}} <p> <button class="btn btn-success btn-lg btn-block" type="submit" value="Pay Now!"> <i class="fa fa-plus-circle fa-lg"></i> Pay Now! </button> </p> </div> </div> </form> ``` When clicking the submit button the customer gets redirected to the Paystack site. So now we've redirected the customer to Paystack. The customer did some actions there (hopefully he or she paid the order) and now gets redirected back to our shop site. Paystack will redirect the customer to the url of the route that is specified in the Callback URL of the Web Hooks section on Paystack dashboard. We must validate if the redirect to our site is a valid request (we don't want imposters to wrongfully place non-paid order). In the controller that handles the request coming from the payment provider, we have `Paystack::getPaymentData()` - This function calls the verification methods and ensure it is a valid transaction else it throws an exception. You can test with these details ```bash Card Number: 4123450131001381 Expiry Date: any date in the future CVV: 883 ``` ## Todo * Charge Returning Customers * Add Comprehensive Tests * Implement Transaction Dashboard to see all of the transactions in your laravel app ## Contributing Please feel free to fork this package and contribute by submitting a pull request to enhance the functionalities. ## How can I thank you? Why not star the github repo? I'd love the attention! Why not share the link for this repository on Twitter or HackerNews? Spread the word! Don't forget to [follow me on twitter](https://twitter.com/unicodeveloper)! Thanks! Prosper Otemuyiwa. ## License The MIT License (MIT). Please see [License File](LICENSE.md) for more information. laravel-paystack/tests/PaystackTest.php 0000644 00000002675 15002141524 0014305 0 ustar 00 <?php /* * This file is part of the Laravel Paystack package. * * (c) Prosper Otemuyiwa <prosperotemuyiwa@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Unicodeveloper\Paystack\Test; use Mockery as m; use GuzzleHttp\Client; use PHPUnit\Framework\TestCase; use Unicodeveloper\Paystack\Paystack; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Facade as Facade; class PaystackTest extends TestCase { protected $paystack; public function setUp(): void { $this->paystack = m::mock('Unicodeveloper\Paystack\Paystack'); $this->mock = m::mock('GuzzleHttp\Client'); } public function tearDown(): void { m::close(); } public function testAllCustomersAreReturned() { $array = $this->paystack->shouldReceive('getAllCustomers')->andReturn(['prosper']); $this->assertEquals('array', gettype(array($array))); } public function testAllTransactionsAreReturned() { $array = $this->paystack->shouldReceive('getAllTransactions')->andReturn(['transactions']); $this->assertEquals('array', gettype(array($array))); } public function testAllPlansAreReturned() { $array = $this->paystack->shouldReceive('getAllPlans')->andReturn(['intermediate-plan']); $this->assertEquals('array', gettype(array($array))); } } laravel-paystack/tests/HelpersTest.php 0000644 00000001174 15002141524 0014121 0 ustar 00 <?php namespace Unicodeveloper\Paystack\Test; use Mockery as m; use PHPUnit\Framework\TestCase; class HelpersTest extends TestCase { protected $paystack; public function setUp(): void { $this->paystack = m::mock('Unicodeveloper\Paystack\Paystack'); $this->mock = m::mock('GuzzleHttp\Client'); } public function tearDown(): void { m::close(); } /** * Tests that helper returns * * @test * @return void */ function it_returns_instance_of_paystack () { $this->assertInstanceOf("Unicodeveloper\Paystack\Paystack", $this->paystack); } } laravel-paystack/src/Paystack.php 0000644 00000047667 15002141524 0013104 0 ustar 00 <?php /* * This file is part of the Laravel Paystack package. * * (c) Prosper Otemuyiwa <prosperotemuyiwa@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Unicodeveloper\Paystack; use GuzzleHttp\Client; use Illuminate\Support\Facades\Config; use Unicodeveloper\Paystack\Exceptions\IsNullException; use Unicodeveloper\Paystack\Exceptions\PaymentVerificationFailedException; class Paystack { /** * Transaction Verification Successful */ const VS = 'Verification successful'; /** * Invalid Transaction reference */ const ITF = "Invalid transaction reference"; /** * Issue Secret Key from your Paystack Dashboard * @var string */ protected $secretKey; /** * Instance of Client * @var Client */ protected $client; /** * Response from requests made to Paystack * @var mixed */ protected $response; /** * Paystack API base Url * @var string */ protected $baseUrl; /** * Authorization Url - Paystack payment page * @var string */ protected $authorizationUrl; public function __construct() { $this->setKey(); $this->setBaseUrl(); $this->setRequestOptions(); } /** * Get Base Url from Paystack config file */ public function setBaseUrl() { $this->baseUrl = Config::get('paystack.paymentUrl'); } /** * Get secret key from Paystack config file */ public function setKey() { $this->secretKey = Config::get('paystack.secretKey'); } /** * Set options for making the Client request */ private function setRequestOptions() { $authBearer = 'Bearer ' . $this->secretKey; $this->client = new Client( [ 'base_uri' => $this->baseUrl, 'headers' => [ 'Authorization' => $authBearer, 'Content-Type' => 'application/json', 'Accept' => 'application/json' ] ] ); } /** * Initiate a payment request to Paystack * Included the option to pass the payload to this method for situations * when the payload is built on the fly (not passed to the controller from a view) * @return Paystack */ public function makePaymentRequest($data = null) { if ($data == null) { $quantity = intval(request()->quantity ?? 1); $data = array_filter([ "amount" => intval(request()->amount) * $quantity, "reference" => request()->reference, "email" => request()->email, "plan" => request()->plan, "first_name" => request()->first_name, "last_name" => request()->last_name, "callback_url" => request()->callback_url, "currency" => (request()->currency != "" ? request()->currency : "NGN"), /* Paystack allows for transactions to be split into a subaccount - The following lines trap the subaccount ID - as well as the ammount to charge the subaccount (if overriden in the form) both values need to be entered within hidden input fields */ "subaccount" => request()->subaccount, "transaction_charge" => request()->transaction_charge, /** * Paystack allows for transaction to be split into multi accounts(subaccounts) * The following lines trap the split ID handling the split * More details here: https://paystack.com/docs/payments/multi-split-payments/#using-transaction-splits-with-payments */ "split_code" => request()->split_code, /** * Paystack allows transaction to be split into multi account(subaccounts) on the fly without predefined split * form need an input field: <input type="hidden" name="split" value="{{ json_encode($split) }}" > * array must be set up as: * $split = [ * "type" => "percentage", * "currency" => "KES", * "subaccounts" => [ * { "subaccount" => "ACCT_li4p6kte2dolodo", "share" => 10 }, * { "subaccount" => "ACCT_li4p6kte2dolodo", "share" => 30 }, * ], * "bearer_type" => "all", * "main_account_share" => 70, * ] * More details here: https://paystack.com/docs/payments/multi-split-payments/#dynamic-splits */ "split" => request()->split, /* * to allow use of metadata on Paystack dashboard and a means to return additional data back to redirect url * form need an input field: <input type="hidden" name="metadata" value="{{ json_encode($array) }}" > * array must be set up as: * $array = [ 'custom_fields' => [ * ['display_name' => "Cart Id", "variable_name" => "cart_id", "value" => "2"], * ['display_name' => "Sex", "variable_name" => "sex", "value" => "female"], * . * . * . * ] * ] */ 'metadata' => request()->metadata ]); } $this->setHttpResponse('/transaction/initialize', 'POST', $data); return $this; } /** * @param string $relativeUrl * @param string $method * @param array $body * @return Paystack * @throws IsNullException */ private function setHttpResponse($relativeUrl, $method, $body = []) { if (is_null($method)) { throw new IsNullException("Empty method not allowed"); } $this->response = $this->client->{strtolower($method)}( $this->baseUrl . $relativeUrl, ["body" => json_encode($body)] ); return $this; } /** * Get the authorization url from the callback response * @return Paystack */ public function getAuthorizationUrl($data = null) { $this->makePaymentRequest($data); $this->url = $this->getResponse()['data']['authorization_url']; return $this; } /** * Get the authorization callback response * In situations where Laravel serves as an backend for a detached UI, the api cannot redirect * and might need to take different actions based on the success or not of the transaction * @return array */ public function getAuthorizationResponse($data) { $this->makePaymentRequest($data); $this->url = $this->getResponse()['data']['authorization_url']; return $this->getResponse(); } /** * Hit Paystack Gateway to Verify that the transaction is valid */ private function verifyTransactionAtGateway($transaction_id = null) { $transactionRef = $transaction_id ?? request()->query('trxref'); $relativeUrl = "/transaction/verify/{$transactionRef}"; $this->response = $this->client->get($this->baseUrl . $relativeUrl, []); } /** * True or false condition whether the transaction is verified * @return boolean */ public function isTransactionVerificationValid($transaction_id = null) { $this->verifyTransactionAtGateway($transaction_id); $result = $this->getResponse()['message']; switch ($result) { case self::VS: $validate = true; break; case self::ITF: $validate = false; break; default: $validate = false; break; } return $validate; } /** * Get Payment details if the transaction was verified successfully * @return json * @throws PaymentVerificationFailedException */ public function getPaymentData() { if ($this->isTransactionVerificationValid()) { return $this->getResponse(); } else { throw new PaymentVerificationFailedException("Invalid Transaction Reference"); } } /** * Fluent method to redirect to Paystack Payment Page */ public function redirectNow() { return redirect($this->url); } /** * Get Access code from transaction callback respose * @return string */ public function getAccessCode() { return $this->getResponse()['data']['access_code']; } /** * Generate a Unique Transaction Reference * @return string */ public function genTranxRef() { return TransRef::getHashedToken(); } /** * Get all the customers that have made transactions on your platform * @return array */ public function getAllCustomers() { $this->setRequestOptions(); return $this->setHttpResponse("/customer", 'GET', [])->getData(); } /** * Get all the plans that you have on Paystack * @return array */ public function getAllPlans() { $this->setRequestOptions(); return $this->setHttpResponse("/plan", 'GET', [])->getData(); } /** * Get all the transactions that have happened overtime * @return array */ public function getAllTransactions() { $this->setRequestOptions(); return $this->setHttpResponse("/transaction", 'GET', [])->getData(); } /** * Get the whole response from a get operation * @return array */ private function getResponse() { return json_decode($this->response->getBody(), true); } /** * Get the data response from a get operation * @return array */ private function getData() { return $this->getResponse()['data']; } /** * Create a plan */ public function createPlan() { $data = [ "name" => request()->name, "description" => request()->desc, "amount" => intval(request()->amount), "interval" => request()->interval, "send_invoices" => request()->send_invoices, "send_sms" => request()->send_sms, "currency" => request()->currency, ]; $this->setRequestOptions(); return $this->setHttpResponse("/plan", 'POST', $data)->getResponse(); } /** * Fetch any plan based on its plan id or code * @param $plan_code * @return array */ public function fetchPlan($plan_code) { $this->setRequestOptions(); return $this->setHttpResponse('/plan/' . $plan_code, 'GET', [])->getResponse(); } /** * Update any plan's details based on its id or code * @param $plan_code * @return array */ public function updatePlan($plan_code) { $data = [ "name" => request()->name, "description" => request()->desc, "amount" => intval(request()->amount), "interval" => request()->interval, "send_invoices" => request()->send_invoices, "send_sms" => request()->send_sms, "currency" => request()->currency, ]; $this->setRequestOptions(); return $this->setHttpResponse('/plan/' . $plan_code, 'PUT', $data)->getResponse(); } /** * Create a customer */ public function createCustomer() { $data = [ "email" => request()->email, "first_name" => request()->fname, "last_name" => request()->lname, "phone" => request()->phone, "metadata" => request()->additional_info /* key => value pairs array */ ]; $this->setRequestOptions(); return $this->setHttpResponse('/customer', 'POST', $data)->getResponse(); } /** * Fetch a customer based on id or code * @param $customer_id * @return array */ public function fetchCustomer($customer_id) { $this->setRequestOptions(); return $this->setHttpResponse('/customer/' . $customer_id, 'GET', [])->getResponse(); } /** * Update a customer's details based on their id or code * @param $customer_id * @return array */ public function updateCustomer($customer_id) { $data = [ "email" => request()->email, "first_name" => request()->fname, "last_name" => request()->lname, "phone" => request()->phone, "metadata" => request()->additional_info /* key => value pairs array */ ]; $this->setRequestOptions(); return $this->setHttpResponse('/customer/' . $customer_id, 'PUT', $data)->getResponse(); } /** * Export transactions in .CSV * @return array */ public function exportTransactions() { $data = [ "from" => request()->from, "to" => request()->to, 'settled' => request()->settled ]; $this->setRequestOptions(); return $this->setHttpResponse('/transaction/export', 'GET', $data)->getResponse(); } /** * Create a subscription to a plan from a customer. */ public function createSubscription() { $data = [ "customer" => request()->customer, //Customer email or code "plan" => request()->plan, "authorization" => request()->authorization_code ]; $this->setRequestOptions(); return $this->setHttpResponse('/subscription', 'POST', $data)->getResponse(); } /** * Get all the subscriptions made on Paystack. * * @return array */ public function getAllSubscriptions() { $this->setRequestOptions(); return $this->setHttpResponse("/subscription", 'GET', [])->getData(); } /** * Get customer subscriptions * * @param integer $customer_id * @return array */ public function getCustomerSubscriptions($customer_id) { $this->setRequestOptions(); return $this->setHttpResponse('/subscription?customer=' . $customer_id, 'GET', [])->getData(); } /** * Get plan subscriptions * * @param integer $plan_id * @return array */ public function getPlanSubscriptions($plan_id) { $this->setRequestOptions(); return $this->setHttpResponse('/subscription?plan=' . $plan_id, 'GET', [])->getData(); } /** * Enable a subscription using the subscription code and token * @return array */ public function enableSubscription() { $data = [ "code" => request()->code, "token" => request()->token, ]; $this->setRequestOptions(); return $this->setHttpResponse('/subscription/enable', 'POST', $data)->getResponse(); } /** * Disable a subscription using the subscription code and token * @return array */ public function disableSubscription() { $data = [ "code" => request()->code, "token" => request()->token, ]; $this->setRequestOptions(); return $this->setHttpResponse('/subscription/disable', 'POST', $data)->getResponse(); } /** * Fetch details about a certain subscription * @param mixed $subscription_id * @return array */ public function fetchSubscription($subscription_id) { $this->setRequestOptions(); return $this->setHttpResponse('/subscription/' . $subscription_id, 'GET', [])->getResponse(); } /** * Create pages you can share with users using the returned slug */ public function createPage() { $data = [ "name" => request()->name, "description" => request()->description, "amount" => request()->amount ]; $this->setRequestOptions(); return $this->setHttpResponse('/page', 'POST', $data)->getResponse(); } /** * Fetches all the pages the merchant has * @return array */ public function getAllPages() { $this->setRequestOptions(); return $this->setHttpResponse('/page', 'GET', [])->getResponse(); } /** * Fetch details about a certain page using its id or slug * @param mixed $page_id * @return array */ public function fetchPage($page_id) { $this->setRequestOptions(); return $this->setHttpResponse('/page/' . $page_id, 'GET', [])->getResponse(); } /** * Update the details about a particular page * @param $page_id * @return array */ public function updatePage($page_id) { $data = [ "name" => request()->name, "description" => request()->description, "amount" => request()->amount ]; $this->setRequestOptions(); return $this->setHttpResponse('/page/' . $page_id, 'PUT', $data)->getResponse(); } /** * Creates a subaccount to be used for split payments . Required params are business_name , settlement_bank , account_number , percentage_charge * * @return array */ public function createSubAccount() { $data = [ "business_name" => request()->business_name, "settlement_bank" => request()->settlement_bank, "account_number" => request()->account_number, "percentage_charge" => request()->percentage_charge, "primary_contact_email" => request()->primary_contact_email, "primary_contact_name" => request()->primary_contact_name, "primary_contact_phone" => request()->primary_contact_phone, "metadata" => request()->metadata, 'settlement_schedule' => request()->settlement_schedule ]; $this->setRequestOptions(); return $this->setHttpResponse('/subaccount', 'POST', array_filter($data))->getResponse(); } /** * Fetches details of a subaccount * @param subaccount code * @return array */ public function fetchSubAccount($subaccount_code) { $this->setRequestOptions(); return $this->setHttpResponse("/subaccount/{$subaccount_code}", "GET", [])->getResponse(); } /** * Lists all the subaccounts associated with the account * @param $per_page - Specifies how many records to retrieve per page , $page - SPecifies exactly what page to retrieve * @return array */ public function listSubAccounts($per_page, $page) { $this->setRequestOptions(); return $this->setHttpResponse("/subaccount/?perPage=" . (int) $per_page . "&page=" . (int) $page, "GET")->getResponse(); } /** * Updates a subaccount to be used for split payments . Required params are business_name , settlement_bank , account_number , percentage_charge * @param subaccount code * @return array */ public function updateSubAccount($subaccount_code) { $data = [ "business_name" => request()->business_name, "settlement_bank" => request()->settlement_bank, "account_number" => request()->account_number, "percentage_charge" => request()->percentage_charge, "description" => request()->description, "primary_contact_email" => request()->primary_contact_email, "primary_contact_name" => request()->primary_contact_name, "primary_contact_phone" => request()->primary_contact_phone, "metadata" => request()->metadata, 'settlement_schedule' => request()->settlement_schedule ]; $this->setRequestOptions(); return $this->setHttpResponse("/subaccount/{$subaccount_code}", "PUT", array_filter($data))->getResponse(); } } laravel-paystack/src/Exceptions/IsNullException.php 0000644 00000000554 15002141524 0016513 0 ustar 00 <?php /* * This file is part of the Laravel Paystack package. * * (c) Prosper Otemuyiwa <prosperotemuyiwa@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Unicodeveloper\Paystack\Exceptions; use Exception; class IsNullException extends Exception { } laravel-paystack/src/Exceptions/PaymentVerificationFailedException.php 0000644 00000000577 15002141524 0022377 0 ustar 00 <?php /* * This file is part of the Laravel Paystack package. * * (c) Prosper Otemuyiwa <prosperotemuyiwa@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Unicodeveloper\Paystack\Exceptions; use Exception; class PaymentVerificationFailedException extends Exception { } laravel-paystack/src/Support/helpers.php 0000644 00000000176 15002141524 0014423 0 ustar 00 <?php if (! function_exists("paystack")) { function paystack() { return app()->make('laravel-paystack'); } } laravel-paystack/src/TransRef.php 0000644 00000004660 15002141524 0013033 0 ustar 00 <?php /* * This file is part of the Laravel Paystack package. * * (c) Prosper Otemuyiwa <prosperotemuyiwa@gmail.com> * * Source http://stackoverflow.com/a/13733588/179104 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Unicodeveloper\Paystack; class TransRef { /** * Get the pool to use based on the type of prefix hash * @param string $type * @return string */ private static function getPool($type = 'alnum') { switch ($type) { case 'alnum': $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'alpha': $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'hexdec': $pool = '0123456789abcdef'; break; case 'numeric': $pool = '0123456789'; break; case 'nozero': $pool = '123456789'; break; case 'distinct': $pool = '2345679ACDEFHJKLMNPRSTUVWXYZ'; break; default: $pool = (string) $type; break; } return $pool; } /** * Generate a random secure crypt figure * @param integer $min * @param integer $max * @return integer */ private static function secureCrypt($min, $max) { $range = $max - $min; if ($range < 0) { return $min; // not so random... } $log = log($range, 2); $bytes = (int) ($log / 8) + 1; // length in bytes $bits = (int) $log + 1; // length in bits $filter = (int) (1 << $bits) - 1; // set all lower bits to 1 do { $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes))); $rnd = $rnd & $filter; // discard irrelevant bits } while ($rnd >= $range); return $min + $rnd; } /** * Finally, generate a hashed token * @param integer $length * @return string */ public static function getHashedToken($length = 25) { $token = ""; $max = strlen(static::getPool()); for ($i = 0; $i < $length; $i++) { $token .= static::getPool()[static::secureCrypt(0, $max)]; } return $token; } } laravel-paystack/src/Facades/Paystack.php 0000644 00000001055 15002141524 0014407 0 ustar 00 <?php /* * This file is part of the Laravel Paystack package. * * (c) Prosper Otemuyiwa <prosperotemuyiwa@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Unicodeveloper\Paystack\Facades; use Illuminate\Support\Facades\Facade; class Paystack extends Facade { /** * Get the registered name of the component * @return string */ protected static function getFacadeAccessor() { return 'laravel-paystack'; } } laravel-paystack/src/PaystackServiceProvider.php 0000644 00000002222 15002141524 0016112 0 ustar 00 <?php /* * This file is part of the Laravel Paystack package. * * (c) Prosper Otemuyiwa <prosperotemuyiwa@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Unicodeveloper\Paystack; use Illuminate\Support\ServiceProvider; class PaystackServiceProvider extends ServiceProvider { /* * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Publishes all the config file this package needs to function */ public function boot() { $config = realpath(__DIR__.'/../resources/config/paystack.php'); $this->publishes([ $config => config_path('paystack.php') ]); } /** * Register the application services. */ public function register() { $this->app->bind('laravel-paystack', function () { return new Paystack; }); } /** * Get the services provided by the provider * @return array */ public function provides() { return ['laravel-paystack']; } } laravel-paystack/LICENSE.md 0000644 00000002173 15002141524 0011410 0 ustar 00 # The MIT License (MIT) Copyright (c) 2015 Prosper Otemuyiwa <prosperotemuyiwa@gmail.com> > Permission is hereby granted, free of charge, to any person obtaining a copy > of this software and associated documentation files (the "Software"), to deal > in the Software without restriction, including without limitation the rights > to use, copy, modify, merge, publish, distribute, sublicense, and/or sell > copies of the Software, and to permit persons to whom the Software is > furnished to do so, subject to the following conditions: > > The above copyright notice and this permission notice shall be included in > all copies or substantial portions of the Software. > > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, > FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE > AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER > LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, > OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN > THE SOFTWARE. laravel-paystack/CHANGELOG.md 0000644 00000000503 15002141524 0011610 0 ustar 00 # Changelog All Notable changes to `laravel-paystack` will be documented in this file ## 2015-11-04 - Initial release ## 2020-05-23 - Support for Laravel 7 - Support for splitting payments into subaccounts - Support for more than one currency. Now you can use USD! - Support for multiple quantities - Support for helpers
| ver. 1.4 |
Github
|
.
| PHP 8.2.28 | Generation time: 0 |
proxy
|
phpinfo
|
Settings