Cakephp, PHP

Sử dụng Squareup để thanh toán bằng CakePHP

– B1: Tạo tài khoản square taị https://squareup.com/ để có thể sử dụng SDK.
+ Sau khi đăng kí tài khoản square, chúng ta truy cập https://developer.squareup.com/apps để tạo app quản lý tương ứng với project của mình
+ Sau khi tạo app, ta sẽ có các key để sử dụng (Sandbox Application ID, Sandbox Access Token, Sandbox Application Secret)

– B2: Cài đặt SDK vào dự án cakephp bằng cách chạy lệnh

composer require square/square

– B3: Sử dụng các hàm trong sdk đã cài đặt để kết nối tới square và sử dụng tính năng thanh toán bằng các thẻ visa, master card,…
+ Để kết nối tới square, ta cần có access token được cung cấp khi tạo app, và môi trường kết nối sẽ là sandbox (hoặc product).

$client = new SquareClient([

‘accessToken’ => ‘YOUR_ACCESS TOKEN’,

‘environment’ => Environment::SANDBOX,

]);

+ Sử dụng hàm listLocations để lấy ra location id cần trong thanh toán:

$locationId = “”;

$location = $client->getLocationsApi()->listLocations();

if (!$location->getErrors()) {

$data = $location->getResult();

$dataLocation = $data->getLocations();

$locationId = $dataLocation[0]->id;

}

+ Khởi tạo thanh toán, dùng hàm getCheckoutApi:

$checkout_api = $client->getCheckoutApi();

+ Sử dụng hàm Money, OrderLineItem để tạo các item trong hoá đơn thanh toán:

$money_A = new Money();

$money_A->setCurrency(‘USD’);

$money_A->setAmount(500);

$item_A = new OrderLineItem(1);

$item_A->setName(‘Test Item A’);

$item_A->setBasePriceMoney($money_A);

$item_A->setNote(‘Note of item A’);

+ Tạo hoá đơn bằng hàm Order và CreateOrderRequest:

$order = new Order($location_id);

$order->setLineItems([$item_A, $item_B]);

$create_order_request = new CreateOrderRequest();

$create_order_request->setOrder($order);

+ Sau khi đã có hoá đơn, để redirect tới màn hình thành toán thẻ điển tự, ta sử dụng hàm CreateCheckoutRequest và createCheckout, và sao đó dùng hàm getCheckoutPageUrl để redirect tới màn hình thanh toán thẻ:
->Chú ý:
*Khi sử dụng CreateCheckoutRequest ta có thể cài đặt redirect url mong muốn bằng cách setRedirectUrl, khi thanh toán thành công, project sẽ đc redirect về trang đã cái đặt.
*Ngoài ra có thể sử dụng setNote để cài đặt tên của hoá đơn được lưu trong square app.

$checkout_request = new CreateCheckoutRequest(uniqid(), $create_order_request);

$checkout_request->setRedirectUrl(‘http://localhost/test_quare/square/’);

$checkout_request->setNote(‘Test Order’);

$response = $checkout_api->createCheckout($location_id, $checkout_request);

if (!$response->isError()) {

$this->redirect($response->getResult()->getCheckout()->getCheckoutPageUrl());

}

=>Một số thôgn tin thẻ để test thanh toán tham khảo tại: https://developer.squareup.com/docs/testing/test-values?q=card%20file
=>Tìm hiểu thêm về SDK tại: https://github.com/square/connect-api-examples/tree/master/connect-examples/v2/