FlowRequestBuilder.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. // Copyright 2019 Hackware SpA <human@hackware.cl>
  3. // This file is part of "Hackware Web Services Payment" and licensed under
  4. // the terms of the GNU Affero General Public License version 3, or (at your
  5. // option) a later version. You should have received a copy of this license
  6. // along with the software. If not, see <https://www.gnu.org/licenses/>.
  7. namespace Hawese\Payment\Gateways;
  8. use Hawese\Payment\Support\Http as HttpSupport;
  9. use UnexpectedValueException;
  10. class FlowRequestBuilder extends AbstractRequestBuilder
  11. {
  12. const ENDPOINT = 'https://www.flow.cl/api';
  13. const TEST_ENDPOINT = 'https://sandbox.flow.cl/api';
  14. private $credentials;
  15. public function __construct(...$args)
  16. {
  17. parent::__construct(...$args);
  18. $this->credentials = (object) config('gateways.flow.credentials');
  19. $this->addDefaultParams();
  20. }
  21. protected function getEndpoint(): string
  22. {
  23. if (config('gateways.flow.test_mode')) {
  24. return self::TEST_ENDPOINT;
  25. }
  26. return self::ENDPOINT;
  27. }
  28. private function addDefaultParams(): void
  29. {
  30. $params = array_merge($this->getBodyOrQueryParams(), [
  31. 'apiKey' => $this->credentials->apiKey
  32. ]);
  33. if ($this->method == 'GET') {
  34. $this->uri = (string) $this->buildUri()->withQuery(
  35. HttpSupport::buildUriQuery($params)
  36. );
  37. $this->uri .= '&s=' . $this->getSignature();
  38. } elseif ($this->method == 'POST') {
  39. $this->bodyParams = $params;
  40. $this->bodyParams['s'] = $this->getSignature();
  41. } else {
  42. throw new UnexpectedValueException(
  43. "Request method $this->method is unsuported.",
  44. 2002
  45. );
  46. }
  47. }
  48. private function getSignature(): string
  49. {
  50. return hash_hmac(
  51. 'sha256',
  52. $this->toSign(),
  53. $this->credentials->secretKey
  54. );
  55. }
  56. private function toSign(): string
  57. {
  58. $params = $this->getBodyOrQueryParams();
  59. ksort($params);
  60. if ($this->method == 'GET') {
  61. return HttpSupport::buildUriQuery($params);
  62. }
  63. // POST
  64. array_walk($params, function (&$item, $key) {
  65. $item = "$key=$item";
  66. });
  67. return implode('&', $params);
  68. }
  69. }