/
var
/
www
/
html
/
plugin-techloyce
/
Modules
/
POS
/
Services
/
Upload File
HOME
<?php namespace Modules\POS\Services; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Storage; use Modules\POS\Contracts\SquarePOSContract; use Modules\CRM\Contracts\ZohoInventoryContract; use square\connect; use Carbon\Carbon; class SquarePOSService implements SquarePOSContract { public $request; public $response; public function __construct() { $this->response = ['status'=>false]; } public function authorize(Request $request) { $this->request = $request; // Get client, secret for API from config $credentials = config('pos.service:SquarePOS'); if(isset($request->app_authorize) && $request->app_authorize==1){ $redirect_uri = url('/pos/authorize_callback'); if($credentials['is_sandbox']){ $client_id = $credentials['sandbox_application_id']; $setHost = $credentials['sandbox_setHost']; }else{ $client_id = $credentials['application_id']; $setHost = $credentials['setHost']; } $authorize_url = $setHost.'/oauth2/authorize?client_id='.$client_id.'&redirect_uri='.$redirect_uri.'&access_type='.$credentials['access_type'].'&scope='.$credentials['scope']; $this->response['status'] = true; $this->response['data'] = ['service'=>'SquarePOS','app_authorize'=>$request->app_authorize,'authorize_url'=>$authorize_url]; }else{ //get & check api_key if(isset($credentials['sandbox_access_token']) && $credentials['sandbox_access_token']!=''){ $authorize = true; } if($authorize) { $this->authorized = true; $this->response['status'] = true; $this->response['data'] = ['service'=>'SquarePOS','access_token'=>$credentials['sandbox_access_token']]; } else { $this->response['status'] = false; $this->response['data'] = ['service'=>'SquarePOS','response'=>'API Key not found!']; } } return $this->response; } public function authorize_callback(Request $request){ if ($request->code) { $credentials = config('pos.service:SquarePOS'); if ("code" === $_GET["response_type"]) { // Get the authorization code and use it to call the GetOAuthToken wrapper function. $authorizationCode = $request->code; $res = $this->GetOAuthToken($authorizationCode,$credentials); $token = $res['data']['resource']; $this->response['status'] = true; $this->response['data'] = array( 'service'=>'SquarePOS', "refresh_token" => $token['refresh_token'], "access_token" => $token['access_token'], "expires_in" => $token['expires_in'],//Carbon::now()->addSeconds($token['expires_in']) , "merchantId" => $token['merchantId'], ); }elseif($_GET['error']) { $this->response['status'] = false; // Check to see if the seller clicked the Deny button and handle it as a special case. if(("access_denied" === $_GET["error"]) && ("user_denied" === $_GET["error_description"])) { $this->response['data'] = ['service'=>'SquarePOS','response'=>'You chose to deny access to the app.']; } else { $this->response['data'] = ['service'=>'SquarePOS','response'=>$_GET["error_description"]]; } } } else { $this->response['status'] = false; $this->response['data'] = ['service'=>'SquarePOS','response'=>'Access Denied']; } return $this->response; } public function integrate(Request $request) { // Check if authenticated/authorized // integration here.. // Map data // Sync data // Return response with applicable status [true,false] with data $this->response['status'] = true; $this->response['data'] = [ 'service'=>'SquarePOS', 'integration_status' => true, 'data_synced' => true, ]; return $this->response; } public function getResource(Request $request) { // Check if authenticated/authorized // Make API requests to get resource // Return response with applicable status [true,false] with data $this->response['status'] = true; $this->response['data'] = [ 'service'=>'SquarePOS', 'resource' => [] ]; return $this->response; } // The GetOAuthToken function shows you how to obtain a OAuth access token // with the OAuth API with the authorization code returned to OAuth callback. public function GetOAuthToken($authorizationCode,$credentials) { $redirect_uri = url('/pos/authorize_callback'); if($credentials['is_sandbox']){ $application_id = $credentials['sandbox_application_id']; $application_secret = $credentials['sandbox_application_secret']; $setHost = $credentials['sandbox_setHost']; }else{ $application_id = $credentials['application_id']; $application_secret = $credentials['application_secret']; $setHost = $credentials['setHost']; } // Initialize SquareConnect OAuth API client. $apiConfig = new \SquareConnect\Configuration(); $apiConfig->setHost($setHost); $apiClient = new \SquareConnect\ApiClient($apiConfig); $oauthApi = new \SquareConnect\Api\OAuthApi($apiClient); // Initialize the request parameters for the obtainToken request. $body = new \SquareConnect\Model\ObtainTokenRequest(); $body->setClientId($application_id); $body->setClientSecret($application_secret); $body->setGrantType($credentials['access_type']); $body->setCode($authorizationCode); $body->setRedirectUri($redirect_uri); // Call obtainToken endpoint to get the OAuth tokens. try { $response = $oauthApi->obtainToken($body); } catch (ApiException $e) { $this->response['status'] = false; $this->response['data'] = [ 'service'=>'SquarePOS', 'resource' => ['response'=> "Error Processing Request: obtainToken failed!\n" . $e->getMessage() . "\n" . $e->getResponseBody()]]; } // Extract the tokens from the response. $accessToken = $response->getAccessToken(); $refreshToken = $response->getRefreshToken(); $expiresAt = $response->getExpiresAt(); $merchantId = $response->getMerchantId(); $this->response['status'] = true; $this->response['data'] = [ 'service'=>'SquarePOS', 'resource' => ['access_token'=>$accessToken, 'refresh_token'=>$refreshToken, 'expires_in'=>$expiresAt, 'merchantId'=>$merchantId]]; // Return the tokens along with the expiry date/time and merchant ID. //return array('access_token'=>$accessToken, 'refresh_token'=>$refreshToken, 'expires_in'=>$expiresAt, 'merchantId'=>$merchantId); return $this->response; } public function RenewToken(Request $request, $token){ $redirect_uri = url('/pos/authorize_callback'); $credentials = config('pos.service:SquarePOS'); if($credentials['is_sandbox']){ $application_id = $credentials['sandbox_application_id']; $application_secret = $credentials['sandbox_application_secret']; $setHost = $credentials['sandbox_setHost']; }else{ $application_id = $credentials['application_id']; $application_secret = $credentials['application_secret']; $setHost = $credentials['setHost']; } // Initialize SquareConnect OAuth API client. $apiConfig = new \SquareConnect\Configuration(); $apiConfig->setHost($setHost); $apiClient = new \SquareConnect\ApiClient($apiConfig); $oauthApi = new \SquareConnect\Api\OAuthApi($apiClient); // Initialize the request parameters for the obtainToken request. $body = new \SquareConnect\Model\ObtainTokenRequest(); $body->setClientId($application_id); $body->setClientSecret($application_secret); $body->setGrantType('refresh_token'); if(isset($token['refresh_token'])){ $body->setRefreshToken($token['refresh_token']); $app_expires_in = $token['expires_in']; }else{ $body->setRefreshToken($token->app_refresh_token); $app_expires_in = $token->app_expires_in; } // Call obtainToken endpoint to get the OAuth tokens. if(Carbon::now()->gte($app_expires_in)) { try { $response = $oauthApi->obtainToken($body); } catch (ApiException $e) { $this->response['status'] = false; $this->response['data'] = [ 'service'=>'SquarePOS', 'resource' => ['response'=> "Error Processing Request: obtainToken failed!\n" . $e->getMessage() . "\n" . $e->getResponseBody()]]; } // Extract the tokens from the response. $accessToken = $response->getAccessToken(); $refreshToken = $response->getRefreshToken(); $expiresAt = $response->getExpiresAt(); $merchantId = $response->getMerchantId(); $token->app_refresh_token = $refreshToken; $token->app_access_token = $accessToken; $token->app_expires_in = $expiresAt; $token->save(); }else{ if(isset($token['refresh_token'])){ $accessToken = $token['access_token']; $refreshToken = $token['refresh_token']; $expiresAt = $token['expires_in']; $merchantId = $token['merchantId']; }else{ $accessToken = $token->app_access_token; $refreshToken = $token->app_refresh_token; $expiresAt = $token->app_expires_in; $merchantId = $token->app_id; } } $this->response['status'] = true; $this->response['data'] = [ 'service'=>'SquarePOS', 'resource' => ['access_token'=>$accessToken, 'refresh_token'=>$refreshToken, 'expires_in'=>$expiresAt, 'merchantId'=>$merchantId] ]; return $this->response; } public function get_locations(Request $request,$token){ $credentials = config('pos.service:SquarePOS'); if($credentials['is_sandbox']){ $application_id = $credentials['sandbox_application_id']; $application_secret = $credentials['sandbox_application_secret']; $setHost = $credentials['sandbox_setHost']; }else{ $application_id = $credentials['application_id']; $application_secret = $credentials['application_secret']; $setHost = $credentials['setHost']; } $res = $this->RenewToken($request, $token); $token = $res['data']['resource']; $apiConfig = new \SquareConnect\Configuration(); $apiConfig->setHost($setHost); $apiConfig->setAccessToken($token['access_token']); $apiClient = new \SquareConnect\ApiClient($apiConfig); $apiInstance = new \SquareConnect\Api\LocationsApi($apiClient); try { if(isset($request->location_id)){ $location = $apiInstance->retrieveLocation($request->location_id); $locations[] = $location->getLocation(); }else{ $locations = $apiInstance->listLocations()->getLocations(); } $locations_arr = array(); foreach($locations as $location){ $locations_arr['id'] = $location->getID(); $locations_arr['name'] = $location->getName(); $locations_arr['merchant_id'] = $location->getMerchantId(); $locations_arr['business_name'] = $location->getBusinessName(); $locations_arr['country'] = $location->getCountry(); $locations_arr['status'] = $location->getStatus(); } $this->response['status'] = true; $this->response['data'] = [ 'service'=>'SquarePOS', 'resource' =>$locations_arr ]; } catch (Exception $e) { $this->response['status'] = false; $this->response['data'] = [ 'service'=>'SquarePOS', 'resource' => 'Exception when calling LocationsApi->listLocations: '. $e->getMessage(), ]; } return $this->response; } public function get_items(Request $request,$token){ $credentials = config('pos.service:SquarePOS'); if($credentials['is_sandbox']){ $application_id = $credentials['sandbox_application_id']; $application_secret = $credentials['sandbox_application_secret']; $setHost = $credentials['sandbox_setHost']; }else{ $application_id = $credentials['application_id']; $application_secret = $credentials['application_secret']; $setHost = $credentials['setHost']; } $res = $this->RenewToken($request, $token); $token = $res['data']['resource']; $apiConfig = new \SquareConnect\Configuration(); $apiConfig->setHost($setHost); $apiConfig->setAccessToken($token['access_token']); $apiClient = new \SquareConnect\ApiClient($apiConfig); $apiInstance = new \SquareConnect\Api\CatalogApi($apiClient); $cursor = ""; // string | The pagination cursor returned in the previous response. Leave unset for an initial request. See [Pagination](https://developer.squareup.com/docs/basics/api101/pagination) for more information. $types = "ITEM,ITEM_VARIATION"; // string | An optional case-insensitive, comma-separated list of object types to retrieve, for example `ITEM,ITEM_VARIATION,CATEGORY,IMAGE`. The legal values are taken from the CatalogObjectType enum: `ITEM`, `ITEM_VARIATION`, `CATEGORY`, `DISCOUNT`, `TAX`, `MODIFIER`, `MODIFIER_LIST`, or `IMAGE`. try { $result = $apiInstance->listCatalog($cursor, $types); dd($result); } catch (Exception $e) { echo 'Exception when calling CatalogApi->listCatalog: ', $e->getMessage(), PHP_EOL; } try { $result = $apiInstance->ListCatalog($location_id, $batch_token); dd($result); $this->response['status'] = true; $this->response['data'] = [ 'service'=>'SquarePOS', 'resource' => ['listLocations'=>$result->getLocations()] ]; } catch (Exception $e) { $this->response['status'] = false; $this->response['data'] = [ 'service'=>'SquarePOS', 'resource' => 'Exception when calling LocationsApi->listLocations: '. $e->getMessage(), ]; } dd($this->response); return $this->response; } public function get_customer($request, $customer_id, $token){ $credentials = config('pos.service:SquarePOS'); $res = $this->RenewToken($request, $token); $token = $res['data']['resource']; if($credentials['is_sandbox']){ $application_id = $credentials['sandbox_application_id']; $application_secret = $credentials['sandbox_application_secret']; $setHost = $credentials['sandbox_setHost']; }else{ $application_id = $credentials['application_id']; $application_secret = $credentials['application_secret']; $setHost = $credentials['setHost']; } $apiConfig = new \SquareConnect\Configuration(); $apiConfig->setHost($setHost); $apiConfig->setAccessToken($token['access_token']); $apiClient = new \SquareConnect\ApiClient($apiConfig); $apiInstance = new \SquareConnect\Api\CustomersApi($apiClient); try { $result = $apiInstance->retrieveCustomer($customer_id); dd($result); $this->response['status'] = true; $this->response['data'] = [ 'service'=>'SquarePOS', 'resource' => $result->getCustomer(), ]; } catch (Exception $e) { $this->response['status'] = false; $this->response['data'] = [ 'service'=>'SquarePOS', 'resource' => 'Exception when calling CustomersApi->retrieveCustomer: '. $e->getMessage(), ]; } } public function get_webhook_order(Request $request,$token){ $credentials = config('pos.service:SquarePOS'); $res = $this->RenewToken($request, $token); $token = $res['data']['resource']; if($credentials['is_sandbox']){ $application_id = $credentials['sandbox_application_id']; $application_secret = $credentials['sandbox_application_secret']; $setHost = $credentials['sandbox_setHost']; }else{ $application_id = $credentials['application_id']; $application_secret = $credentials['application_secret']; $setHost = $credentials['setHost']; } $apiConfig = new \SquareConnect\Configuration(); $apiConfig->setHost($setHost); $apiConfig->setAccessToken($token['access_token']); $apiClient = new \SquareConnect\ApiClient($apiConfig); if(isset($request->webhook_data->data->object->order_created)){ $location_id = $request->webhook_data->data->object->order_created->location_id; $order_id = $request->webhook_data->data->object->order_created->order_id;// string | The ID of the orders' associated location. }else{ if(isset($request->webhook_data->data->object->order_fulfillment_updated)){ $location_id = $request->webhook_data->data->object->order_fulfillment_updated->location_id; $order_id = $request->webhook_data->data->object->order_fulfillment_updated->order_id; }else{ $location_id = $request->webhook_data->data->object->order_updated->location_id; $order_id = $request->webhook_data->data->object->order_updated->order_id; } } $apiInstance = new \SquareConnect\Api\OrdersApi($apiClient); $body = new \SquareConnect\Model\BatchRetrieveOrdersRequest(); Storage::put($order_id.'.txt', $order_id); dd($order_id); $body->setOrderIds(array($order_id)); try { $result = $apiInstance->batchRetrieveOrders($location_id, $body); $orders = $result->getOrders(); $CapiInstance = new \SquareConnect\Api\CustomersApi($apiClient); $orders_arr = array(); foreach($orders as $order){ // $orders_arr['id'] = $order->getId(); $orders_arr['LocationId'] = $order->getLocationId(); $orders_arr['ReferenceId']= $order->getReferenceId(); $orders_arr['Source']= $order->getSource();//arr $orders_arr['CustomerId']= $order->getCustomerId(); $result = $CapiInstance->retrieveCustomer($order->getCustomerId()); $Customer = $result->getCustomer(); $customer_arr['first_name'] = $Customer->getGivenName(); $customer_arr['last_name'] = $Customer->getFamilyName(); $customer_arr['contact_name'] = $Customer->getGivenName().' '.$Customer->getFamilyName(); $customer_arr['email'] = $Customer->getEmailAddress(); $customer_arr['contact_type'] = 'customer'; $customer_arr['billing_address']['attention'] = $customer_arr['contact_name']; $customer_arr['billing_address']['address'] = $Customer->getAddress()->getAddressLine1().' '.$Customer->getAddress()->getAddressLine2(); $customer_arr['billing_address']['street2'] = $Customer->getAddress()->getLocality(); $customer_arr['billing_address']['zip'] = $Customer->getAddress()->getPostalCode(); $customer_arr['billing_address']['country'] = $Customer->getAddress()->getCountry(); // $customer_arr['shipping_address']['attention'] = $customer_arr['contact_name']; $customer_arr['shipping_address']['address'] = $Customer->getAddress()->getAddressLine1().' '.$Customer->getAddress()->getAddressLine2(); $customer_arr['shipping_address']['street2'] = $Customer->getAddress()->getLocality(); $customer_arr['shipping_address']['zip'] = $Customer->getAddress()->getPostalCode(); $customer_arr['shipping_address']['country'] = $Customer->getAddress()->getCountry(); $orders_arr['Customer'] = $customer_arr; $orders_arr['LineItems']= $order->getLineItems();//arr $orders_arr['Taxes']= $order->getTaxes();//arr $orders_arr['Discounts']= $order->getDiscounts(); $orders_arr['ServiceCharges']= $order->getServiceCharges(); $orders_arr['Fulfillments']= $order->getFulfillments();//arr $orders_arr['Returns']= $order->getReturns(); $orders_arr['ReturnAmounts']= $order->getReturnAmounts(); $orders_arr['NetAmounts']= $order->getNetAmounts();//arr $orders_arr['RoundingAdjustment']= $order->getRoundingAdjustment(); $orders_arr['Tenders']= $order->getTenders();//arr $orders_arr['Refunds']= $order->getRefunds(); $orders_arr['Metadata']= $order->getMetadata(); $orders_arr['CreatedAt']= $order->getCreatedAt(); $orders_arr['UpdatedAt']= $order->getUpdatedAt(); $orders_arr['ClosedAt']= $order->getClosedAt(); $orders_arr['State']= $order->getState(); $orders_arr['Version']= $order->getVersion(); $orders_arr['TotalMoney']= $order->getTotalMoney();//arr $orders_arr['TotalTaxMoney']= $order->getTotalTaxMoney();//arr $orders_arr['TotalDiscountMoney']= $order->getTotalDiscountMoney();//arr $orders_arr['TotalServiceChargeMoney']= $order->getTotalServiceChargeMoney();//arr //$orders_arr['Rewards']= $order->getRewards();//not working } $request->request->add(['location_id' => $orders_arr['LocationId']]); $res = $this->get_locations($request, $token); $orders_arr['location'] = $res['data']['resource']; $this->response['status'] = true; $this->response['data'] = [ 'service'=>'SquarePOS', 'resource' =>$orders_arr, ]; } catch (Exception $e) { $this->response['status'] = false; $this->response['data'] = [ 'service'=>'SquarePOS', 'resource' => 'Exception when calling result->getOrders: '. $e->getMessage(), ]; } return $this->response; } public function get_webhooks(Request $request,$token){ $this->request = $request; // Get client, secret for API from config $credentials = config('pos.service:SquarePOS'); if($request->webhook_data->type=='order.created'){ $order = $this->get_webhook_order($request, $token); $res = $this->post_webhook_order($request, $token, $order); dd($res); } if($request->webhook_data->type=='order.updated' || $request->webhook_data->type=='order.fulfillment.updated'){ $obj_inv_service = resolve(ZohoInventoryContract::class); $order = $this->get_webhook_order($request, $token); $request->request->add(['order' => $order,'DestinationToken' => $token]); $res = $obj_inv_service->get_saleorder_update($request, $order); } dd('stop'); } public function post_webhook_order(Request $request,$token,$order){ $obj_inv_service = resolve(ZohoInventoryContract::class); /* $SendInventoryServiceReq = new Request(); $SendInventoryServiceReq->setMethod('POST'); $SendInventoryServiceReq->request->add($request); $SendInventoryServiceReq->request->add($token); $SendInventoryServiceReq->request->add($order);*/ $request->request->add(['order' => $order,'DestinationToken' => $token]); $res = $obj_inv_service->get_saleorder($request, $order); return $res; } public function RevokeTokenRequest(Request $request,$token){} }