Giter Site home page Giter Site logo

laravel-square's Introduction

Test Coverage Build and test PHP 8.x Latest Stable Version License


Square integration with Laravel/Lumen >=5.5 built on nikolag/core

  1. Version Compatibility
  2. Installation guide
  3. Customer System
  4. Order System
  5. Examples
  6. Available methods
  7. Contributing
  8. License

Version Compatibility

Old square connect api

Library Version Laravel Version Square Connect Version
2.3.x   >= 5.5 2.20190814 (Square Connect V1)
2.4.x   >= 6.x 2.20190925.0 (Square Connect V2)
2.5.x   >= 7.x 2.20190925.0 (Square Connect V2)
2.6.x   >= 8.x 3.20200528.1 (Square Connect V2)

New square sdk

Library Version Laravel Version Square SDK Version
3.0.x   >= 8.x 17.0.0.20211215
3.1.x   >= 9.x 25.1.0.20230119
3.2.0   >= 10.x 25.1.0.20230119
3.2.x   >= 10.x 29.0.0.20230720

If you are updating from versions below 3.0 then you need to execute: php artisan migrate. This will add some columns required by the library into the tables created by the library, your own tables won't be affected.

Installation guide

composer require nikolag/laravel-square

Note: Due to Laravel Package Discovery, registering service providers and facades manually for this project as of Laravel 5.5 is deprecated and no longer required since the package is adapted to automatically register these stuff for you. But there are still couple of steps to do in order to use this package.


First you have to publish configuration files:

php artisan vendor:publish --tag=nikolag_config

Check configuration files out at config/nikolag.php before continuing.

Important: If for some reason you can't see square driver inside of connections array, you'll have to add it manually. You can find configuration file here and copy everything from inside connections array and append to your connections array inside of published config file (config/nikolag.php)

nikolag configuration
Figure 1. Config file

After finishing with configuration files, you should run migrations with the following command

php artisan migrate

Then add your credentials for Square API inside of .env and also add fully qualified name (namespace) for your classes.

SQUARE_APPLICATION_ID=<YOUR_APPLICATION_ID>
SQUARE_TOKEN=<YOUR_ACCESS_TOKEN>

Customers system

To be able to utilize the customers system for Users, your User class must use HasCustomers trait.

...
use Nikolag\Square\Traits\HasCustomers;

class User extends Model {
  use HasCustomers;
  ...
}

You also need to define user namespace

// .env file
SQUARE_USER_NAMESPACE=<USER_NAMESPACE>

Orders system

To be able to utilize the order system for Users, your Order class must use HasProducts trait and define $table property.

...
use Nikolag\Square\Traits\HasProducts;

class Order extends Model {
  use HasProducts;
  ...

  /**
   * The table associated with the model.
   *
   * @var string
   */
  protected $table = '<TABLE_NAME>';
  ...
}

You also need to define a couple of environment variables

// .env file
SQUARE_ORDER_NAMESPACE=<ORDER_NAMESPACE>
SQUARE_ORDER_IDENTIFIER=<ORDER_IDENTIFIER>
SQUARE_PAYMENT_IDENTIFIER=<ORDER_SQUARE_ID_COLUMN>

Important: SQUARE_PAYMENT_IDENTIFIER represents the name of the column where we will keep the unique ID that Square generates once it saves an Order. This means that you will need to add a new column to your Orders table which will hold that value.

Examples

Simple examples

Simple examples are moved to wiki pages to avoid unnecessary scrolling of README.md.

Examples with customers

Examples with customers are moved to wiki pages to avoid unnecessary scrolling of README.md.

Examples with order

Examples with orders are moved to the wiki pages to avoid unnecessary scrolling of README.md.

All traits and their methods

HasProducts

All methods for this trait are moved to the wiki pages to avoid unnecessary scrolling of README.md.

HasCustomers

All methods for this trait are moved to the wiki pages to avoid unnecessary scrolling of README.md.

All facades and their methods

Square

All methods for this facade are moved to the wiki pages to avoid unnecessary scrolling of README.md.

Contributing

Everyone is welcome to contribute to this repository, simply open up an issue and label the request, whether it is an issue, bug or a feature. For any other inquiries send an email to [email protected]

Contributors

Name Changes Date
@Godlikehobbit Add optional currency parameter to charge function pull request #6 2017-09-12
@PaulJulio Cap square/connect version to resolve deprecation exceptions pull request #27 2019-09-20
@Alex Oleynik Fixes TypeError when updating customers pull request #71 2022-06-28
@qooplmao Adds support for 3DS/SCA pull request #74 2023-01-13

Special thanks to all of the contributors!

License

MIT License

Copyright (c) Nikola Gavrić [email protected]

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-square's People

Contributors

alexoleynik0 avatar fr6 avatar godlikehobbit avatar nikolagavric94 avatar pauljulio avatar pharaohash avatar qooplmao avatar spekulatius avatar stylecibot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

laravel-square's Issues

1071 specified key is too long

I am very new to this kind of stuff, so sorry if I ask dumb questions.

I am following your tutorial on medium.com

I got to where I do the database migration, and it created some tables, but I got a 1071 specified key is too long error for the nikolag_taxes table.

It created the table in my database, but not the appropriate migration entry.

I have customers, customer_user, taxes and transactions for tables. Are there more missing?

I am on Laravel 5.7.27 so I have the default string length variable set at 191.

Thanks.

Database Migration Error

I added the package to my project, setup and migrated. However running the migration command fails.

I am using MySQL ver 14.14

The failure was caused by this line in the "create_nikolag_customers_table" migration.

"$table->string('payment_service_type', 25)->unsigned();"

From my understanding you can't unsign a string. Removing "->unsigned()" fixes my issue.

ps. Thanks for the package, it is going to save me a lot of time.

Laravel 9 support

I just wondered what the timeline is for Laravel 9 support.

Thank you.

How to add a title to the transaction

Hello!

Thanks for your package, it's really useful!
I'm building a booking system on Laravel and want to map orders on Square with data in my system.
I'm using a simple code to charge a customer:

$options = [
          'amount' => $amount
          'source_id' => $request->input('nonce'),
          'location_id' => env('SQUARE_LOCATION_ID'),
          'currency' => 'CAD'
 ];

$transaction = Square::charge($options);

And on the dashboard, all the transactions have the title "Custom Amount".

Is there is a way to change it to some custom message, like in this example?
(https://developer.squareup.com/docs/transactions-api/build-with-transactions)

$chargeBody->setReferenceId("Confirmation #12345");
$chargeBody->setNote("This is (not) a helpful note!");

I want to have a custom title to be "Order #123" to search on my system as well and map orders and payments.

Thanks!

DB Tables not found

Hi!

I just installed your package again, into my project after following the installation instructions when trying to charge a card I get

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'nikolag_transactions' ...

But I cant even find the migrations to create the tables....

Payment into multiple Square Account?

Hello there, Is there any option or features to pay in multiple square accounts at a time. For example in my system when a user paying 200$ it should split into 2/3 accounts(Admin and Vendor). But in this package, I have one option to add square credentials into the config file and all payments going in this account. What should I do now?

PHP 8.2 Support

Any path to have 8.2 support as the package will not install with php 8.2.

How to create an order?

Hi there,

thanks for this package! I am currently trying to implement it into my ordering platform. Essentially, what I am looking for is trying to find a way to create an online order so it will show up in my POS along with all the offline orders.

Almost all of the online orders do not need to be paid for. Hence, I only need to create the order, and no charge I assume.

What would you recommend doing in a scenario like this?

Thanks so much Nikola!

Chris

Can't install on Laravel 8

When I install this package, I got error:
- Installation request for laravel/framework (locked at v8.6.0, required as ^8.0) -> satisfiable by laravel/framework[v8.6.0].
- Installation request for nikolag/laravel-square ^2.5 -> satisfiable by nikolag/laravel-square[2.5.x-dev, v2.5.0].

Installation failed, reverting ./composer.json to its original content.

Thanks for reading!

Error message

Do you know what might be causing this error:
Code:

$options = [
	  'amount' => '1000',
	  'source_id' => request()->nonce,
	  'location_id' => 'my_code_is_here',
	  'currency' => 'USD',
	  'note' => 'Test',
	  'reference_id' => '010101'
	];

Square::charge($options); // Simple charge

Error:

SquareConnect\ApiException
[HTTP/2 400] {"errors": [{"code": "EXPECTED_INTEGER","detail": "Expected an integer value (line 1, character 108)","field": "amount_money.amount","category": "INVALID_REQUEST_ERROR"}]}

Wont install on 5.5.x

tried to run the composer require command and it returns telling me it need 5.4.*

nikolag/square v1.0.1 requires laravel/framework 5.4.* -> satisfiable by laravel/framework[5.4.x-dev,

Customer with ID not found.

Here is my code:

$user = User::firstOrCreate(
	['email'=>$data['email']],
	['first'=>$data['first'],'last'=>$data['last']]
);
$customer = [
	'first_name' => $data['first'],
	'last_name' => $data['last'],
	'email' => $data['email'],
];

Square::setMerchant($user)->setCustomer($customer)->save();

When I run the code against the sandbox api, everything works great. The customer is created and the transaction is attached to the customer. When I switch to live credentials I get:
[HTTP/1.1 404 Not Found] {"errors": [{"code": "NOT_FOUND","detail": "Customer with ID `6XG3GYC5D8VCKE9JEHVVZAKECC` not found.","category": "INVALID_REQUEST_ERROR"}]}

I can't figure out why it works fine in sandbox, but not in live

Minor typo in Examples

Please note that there is a minor typo in the following wiki pages:

  • Examples/Customer Examples.md
  • Examples/Simple Examples.md

The line:
'location_id' => $locationd_id,

should be
'location_id' => $location_id,

Charge with old customer issue

I wanted to charge a customer already created. I passed the customer instance as following:

$customer = $this->hasCustomer($this->email);
if(!$customer){
   $customer = [
        'first_name' => $firstName,
        'last_name' => $lastName,
        'email' => $this->email,
        'phone' => $this->phone,
   ];
}
$user->charge($subTotal, $sourceId, $locationId, $options, $customer, $currency);

Doing so, i get the following error
TypeError: Argument 2 passed to Square\Apis\CustomersApi::updateCustomer() must be an instance of Square\Models\UpdateCustomerRequest, instance of Square\Models\CreateCustomerRequest given

UNAUTHORIZED Token issue!

[HTTP/2 401] {"errors": [{"code": "UNAUTHORIZED","detail": "The Authorization http header of your request was incorrect or expired. The header value is expected to be of the format "Bearer TOKEN" (without quotation marks), where TOKEN is a valid access token (e.g. "Bearer ABC123def456GHI789jkl0"). For more information, see https://developer.squareup.com/docs/build-basics/using-rest-api#set-the-headers .","category": "AUTHENTICATION_ERROR"}]}

Production api is calling instead of Sandbox

my config file is such:

<?php

return [
    
    'default' => 'square',
    'connections' => [
        'square' => [
            'namespace'      => 'Nikolag\Square\SquareService',
            'application_id' => env('SQUARE_SANDBOX_ID'),
            'access_token'   => env('SQUARE_SANDBOX_ACCESS_TOKEN'),
            'sandbox' => true,

            'user' => [
                'namespace'  => env('SQUARE_USER_NAMESPACE', '\App\User'),
                'identifier' => env('SQUARE_USER_IDENTIFIER', 'id'),
            ],

            'order' => [
                'namespace'          => env('SQUARE_ORDER_NAMESPACE', '\App\Order'),
                'identifier'         => env('SQUARE_ORDER_IDENTIFIER', 'id'),
                'service_identifier' => env('SQUARE_PAYMENT_IDENTIFIER', 'payment_service_id'),
            ],
        ],
    ],
];

though "sandbox" is true still the api that is calling is using "https://connect.squareup.com" as baseUrl.

installation issue

I'm unable to download and install the package via composer...i get the following when i attempt

Screen Shot 2020-03-19 at 8 31 50 AM

Update an example from 'card_nonce' to 'source_id'

I updated the plugin to the last version, and it starts to throw an error 'source_id is missing'. As I understand from the code, you changed the 'card_nonce' to 'source_id' field. This code is working for me.

$options = [ 'amount' => $amount, 'source_id' => $request->input('nonce'), 'location_id' => env('SQUARE_LOCATION_ID'), 'currency' => 'CAD' ];

Please, change the examples.

Error Throw When user Exists

This Error gets thrown when setCustomer is called and an existing customer is passed in
{ "message": "Cannot assign Square\\Models\\UpdateCustomerRequest to property Nikolag\\Square\\SquareService::$createCustomerRequest of type Square\\Models\\CreateCustomerRequest", "exception": "TypeError", "file": "/var/www/html/vendor/nikolag/laravel-square/src/SquareService.php", "line": 391, "trace": [ { "file": "/var/www/html/vendor/nikolag/laravel-square/src/SquareService.php", "line": 433, "function": "setCreateCustomerRequest", "class": "Nikolag\\Square\\SquareService", "type": "->" },

After Updating this on the SquareService it works okay ` /**
 * @var CreateCustomerRequest
 */
private CreateCustomerRequest $createCustomerRequest;`

To this 

` /**
 * @var CreateCustomerRequest|UpdateCustomerRequest;
 */
private $createCustomerRequest;`

Am i Doing something wrong 

Undefined variable: exception

When I am charging a card I get

"Undefined variable: exception"

It is telling me Line 135 nikolag/square/src/SquareService.php

Change table name

How do i change the table names: example... from "nikolag_customers" to "customers". Because when i rename the tables i get the error message.

SquareConnect Not found

Got the packacge installed, and when processing a payment, i get

Class 'SquareConnect\Configuration' not found

Setting up an order for gift cards in conjunction with credit card payment

Hello Nikola,
Hope all is well.
As the title suggests, we are having a slightly difficult time creating an order that would handle multiple transactions (combination of gift cards and credit card). At the moment, we calculate the entire amount the customer needs to pay and simply charge them that amount from a cc (eg: $transaction = Square::charge($options)). From our understanding, to split the payment into multiple transactions we need to set up an order, as evident from https://developer.squareup.com/docs/payment-form/gift-cards/part-1 ("Additionally, this guide makes the following assumptions: Your backend supports a check out experience, maintains a checkout payment balance, and can provide an Order or reference ID."). We have tried the following https://github.com/NikolaGavric94/laravel-square/wiki/Order%20Examples, but have been unsuccessful at saving the order properly, as we keep getting "Array to string conversion" error. The only time we were successful at getting the order instance was when we substituted $order with a string "order" in the setOrder method. Anyway, maybe we are misunderstanding something in the first place, as we don't have "products" for the order per say, we simply have the final amount that we need to charge the customer in separate transactions. So what i'm getting at is can/should we use your package with gift cards? Hopefully you can help us out. Thank you.
Our square order that fails to convert array to string:

$products = array([
            'name' => some int,
            'variation_name' => some string,
            'note' => some string,
            'price' => some int - total amount we want to charge,
            'quantity' => some int - 1 for us,
            'reference_id' => some int - holds our own transaction id
        ]);

        $order = array(
            'payment_service_identifier' => null,
            'payment_service_type' => 'square',
            'products' => $products
        );

        $location_id = some string - our location id;

        $squareOrder = Square::setOrder($order, $location_id, 'CAD')->save();

on save() it saves to square

Problem - When I call save() it saves the order to the square vault too

Supposed - To only save the order into the local database.

Reproduce - Square::setOrder($order, 'location_id')->save();

How to take card payment?

I am unable to find code example for payment form. where user has to enter card details and then post to the method which performs the charge?

Pleas epoint me in the right direction.

The code available on the official documentation related to the web payments is in Nodejs.

Undefined Source_id

Good day. Thanks for this wonderful laravel square package. It helps alot

I was trying to run a transaction, but I was getting an undefined source_id at
\vendor\nikolag\laravel-square\src\SquareService.php:229

I don't know why.

I passed the following key value pairs to the square::charge method
amount,
card_nonce
location_id
currency.

Am I suppose to pass some source_id??

Thanks

Undefined variable: fistName

(1/1) ErrorException
Undefined variable: fistName
in SquareCustomer.php (line 155)
at HandleExceptions->handleError(8, 'Undefined variable: fistName', '/Users/nikola/Documents/code/booking-daniel/vendor/nikolag/square/src/SquareCustomer.php', 155, array('firstName' => 'John'))
in SquareCustomer.php (line 155)
at SquareCustomer->setFirstName('John')
in SquareCustomer.php (line 74)
at SquareCustomer->__construct(array('firstName' => 'John', 'lastName' => 'Doe', 'companyName' => 'John Doe LTD.', 'nickname' => 'Johny', 'email' => '[email protected]', 'phone' => '+123325990', 'reference_id' => '555333', 'note' => 'This is a trusted customer.'))
in HomeController.php (line 41)
at HomeController->index()
at call_user_func_array(array(object(HomeController), 'index'), array())
in Controller.php (line 55)
at Controller->callAction('index', array())
in ControllerDispatcher.php (line 44)
at ControllerDispatcher->dispatch(object(Route), object(HomeController), 'index')
in Route.php (line 203)
at Route->runController()
in Route.php (line 160)
at Route->run()
in Router.php (line 574)
at Router->Illuminate\Routing\{closure}(object(Request))
in Pipeline.php (line 30)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in SubstituteBindings.php (line 41)
at SubstituteBindings->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in VerifyCsrfToken.php (line 65)
at VerifyCsrfToken->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in ShareErrorsFromSession.php (line 49)
at ShareErrorsFromSession->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in StartSession.php (line 64)
at StartSession->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in AddQueuedCookiesToResponse.php (line 37)
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in EncryptCookies.php (line 59)
at EncryptCookies->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in Pipeline.php (line 102)
at Pipeline->then(object(Closure))
in Router.php (line 576)
at Router->runRouteWithinStack(object(Route), object(Request))
in Router.php (line 535)
at Router->dispatchToRoute(object(Request))
in Router.php (line 513)
at Router->dispatch(object(Request))
in Kernel.php (line 174)
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
in Pipeline.php (line 30)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in TransformsRequest.php (line 30)
at TransformsRequest->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in TransformsRequest.php (line 30)
at TransformsRequest->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in ValidatePostSize.php (line 27)
at ValidatePostSize->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in CheckForMaintenanceMode.php (line 46)
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in Pipeline.php (line 102)
at Pipeline->then(object(Closure))
in Kernel.php (line 149)
at Kernel->sendRequestThroughRouter(object(Request))
in Kernel.php (line 116)
at Kernel->handle(object(Request))
in index.php (line 53)
at require('/Users/nikola/Documents/code/booking-daniel/public/index.php')
in server.php (line 133)

screen shot 2017-06-16 at 13 53 54

Card fails cause error

If a card fails for whatever reason it throws an exception with APP_DEBUG=True and fails to return response to transaction.
If APP_DEBUG=false it just creates a 500 error.

Nikolag\Square\Exceptions\InvalidSquareZipcodeException: Authorization error: 'ADDRESS_VERIFICATION_FAILURE' in file C:\inetpub\wwwroot\fundraiser\vendor\nikolag\laravel-square\src\SquareService.php on line 181

#0 C:\inetpub\wwwroot\fundraiser\vendor\nikolag\laravel-square\src\SquareService.php(303): Nikolag\Square\SquareService->_handleChargeOrSaveException()

Got error

i got undefined merchant issue can any one help
capture

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.