AwxAfterpay.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. <?php
  2. namespace Longyi\Pay\AwxAfterpay\Payment;
  3. use GuzzleHttp\Client;
  4. use Illuminate\Support\Facades\Log;
  5. use Illuminate\Support\Facades\Storage;
  6. use Webkul\Payment\Payment\Payment;
  7. use Webkul\Sales\Models\Order;
  8. use Webkul\Sales\Repositories\OrderRepository;
  9. use Webkul\Checkout\Facades\Cart;
  10. class AwxAfterpay extends Payment
  11. {
  12. protected $clientId;
  13. protected $apikey;
  14. protected $secret;
  15. protected $currentOrder;
  16. protected $currentInput;
  17. protected $prefix = 'QQS';
  18. protected $tokenCacheKey = 'airwallex_klarna_token';
  19. protected $tokenUrl = 'https://api-demo.airwallex.com/api/v1/authentication/login';
  20. protected $createPaymentUlr = 'https://api-demo.airwallex.com/api/v1/pa/payment_intents/create';
  21. protected $confirmIntentsUlr = 'https://api-demo.airwallex.com/api/v1/pa/payment_intents/{id}/confirm';
  22. protected $captureIntentsUlr = 'https://api-demo.airwallex.com/api/v1/pa/payment_intents/{id}/capture';
  23. protected $paymentIntentsUlr = 'https://api-demo.airwallex.com/api/v1/pa/payment_intents/';
  24. public function __construct()
  25. {
  26. if ($this->getConfigData('mode') == 'live') {
  27. $this->tokenUrl = 'https://api.airwallex.com/api/v1/authentication/login';
  28. $this->createPaymentUlr = 'https://api.airwallex.com/api/v1/pa/payment_intents/create';
  29. $this->confirmIntentsUlr = 'https://api.airwallex.com/api/v1/pa/payment_intents/{id}/confirm';
  30. $this->captureIntentsUlr = 'https://api.airwallex.com/api/v1/pa/payment_intents/{id}/capture';
  31. $this->paymentIntentsUlr = 'https://api.airwallex.com/api/v1/pa/payment_intents/';
  32. }
  33. $this->clientId = $this->getConfigData('client_id');
  34. $this->apikey = $this->getConfigData('secret_id');
  35. $this->secret = $this->getConfigData('webhook_id');
  36. }
  37. /**
  38. * Payment method code
  39. *
  40. * @var string
  41. */
  42. protected $code = 'awxafterpay';
  43. /**
  44. * Get redirect url.
  45. */
  46. public function getRedirectUrl()
  47. {
  48. return route('afterpay.standard.placeOrder');
  49. }
  50. public function setOrder($order = null): self
  51. {
  52. $this->currentOrder = $order;
  53. return $this;
  54. }
  55. public function getOrder()
  56. {
  57. return $this->currentOrder;
  58. }
  59. public function setInput($input = null): self
  60. {
  61. $this->currentInput = $input;
  62. return $this;
  63. }
  64. public function getInput()
  65. {
  66. return $this->currentInput;
  67. }
  68. public function createGatewayOrder()
  69. {
  70. return $this->createPayment($this->getOrder(), ['merchantOrderId' => $this->getOrder()->increment_id], $this->currentInput);
  71. }
  72. public function createPayment($order, $override, $input)
  73. {
  74. $shop = $order->shipping_address;
  75. $bill = $order->billing_address;
  76. $telephone = $shop->phone ?: $bill->phone;
  77. $grandTotal = round($order->grand_total, 2);
  78. $products[] = [
  79. 'name' => 'total',
  80. 'unit_price' => $grandTotal,
  81. 'quantity' => 1
  82. ];
  83. $data = [
  84. 'request_id' => $this->createUuid(),
  85. 'amount' => $grandTotal,
  86. 'descriptor' => $this->prefix,
  87. 'return_url' => $input->paymentSuccessUrl. '?orderId=' . $order->id,
  88. 'merchant_order_id' => $this->prefix . $override['merchantOrderId'],
  89. 'currency' => $order->order_currency_code,
  90. 'customer' => [
  91. 'email' => $order->customer_email,
  92. 'first_name' => $order->customer_first_name,
  93. 'last_name' => $order->customer_last_name,
  94. 'phone_number' => $telephone
  95. ],
  96. // 'metadata' => $cart['items'],
  97. 'order' => [
  98. 'products' => $products,
  99. 'shipping' => [
  100. 'address' => [
  101. 'city' => $shop->city,
  102. 'postcode' => $shop->postcode,
  103. 'state' => $shop->state,
  104. 'country_code' => $shop->country,
  105. 'street' => $shop->address,
  106. ],
  107. 'first_name' => $shop->first_name,
  108. 'last_name' => $shop->last_name,
  109. 'phone_number' => $shop->phone,
  110. 'email' => $shop->email
  111. ],
  112. ]
  113. ];
  114. $client = new Client();
  115. $response = $client->request('POST', $this->createPaymentUlr, [
  116. 'headers' => [
  117. 'Accept' => 'application/json',
  118. 'Content-Type' => 'application/json',
  119. 'Authorization' => 'Bearer '.$this->getToken()
  120. ],
  121. 'json' => $data,
  122. 'timeout' => 30,
  123. 'verify' => false
  124. ]);
  125. $responseBody = $response->getBody()->getContents();
  126. Log::channel('payment')->info('AwxAfterpay createPayment response', [
  127. 'order_id' => $order->increment_id ?? null,
  128. 'status' => $response->getStatusCode(),
  129. 'body' => $responseBody,
  130. ]);
  131. $resultObject = json_decode($responseBody);
  132. if (empty($resultObject->id)) {
  133. throw new \Exception($resultObject->details->original_response_message ?:$resultObject->message);
  134. } else {
  135. $id = $resultObject->id;
  136. $confirmResultObject = $this->confirmRequest($id, $order);
  137. if (empty($confirmResultObject->next_action->url)) {
  138. throw new \Exception($confirmResultObject->details->original_response_message ?:$confirmResultObject->message);
  139. }
  140. return $confirmResultObject->next_action->url;
  141. }
  142. }
  143. public function confirmRequest($paymentIntentId, $order)
  144. {
  145. $bill = $order->billing_address;
  146. $data = [
  147. 'request_id' => $this->createUuid(),
  148. 'payment_method' => [
  149. 'type' => 'afterpay',
  150. 'afterpay' => [
  151. 'shopper_email' => $bill->email,
  152. 'billing' => [
  153. 'first_name' => $bill->first_name,
  154. 'last_name' => $bill->last_name,
  155. 'phone_number' => $bill->phone,
  156. 'address' => [
  157. 'country_code' => $bill->country,
  158. 'city' => $bill->city,
  159. 'street' => $bill->address,
  160. 'postcode' => $bill->postcode,
  161. 'state' => $bill->state
  162. ],
  163. ],
  164. ]
  165. ]
  166. ];
  167. $client = new Client();
  168. $response = $client->request('POST',
  169. str_replace('{id}', $paymentIntentId, $this->confirmIntentsUlr),
  170. [
  171. 'headers' => [
  172. 'Accept' => 'application/json',
  173. 'Content-Type' => 'application/json',
  174. 'Authorization' => 'Bearer '.$this->getToken()
  175. ],
  176. 'json' => $data,
  177. 'timeout' => 30,
  178. 'verify' => false
  179. ]);
  180. $responseBody = $response->getBody()->getContents();
  181. Log::channel('payment')->info('AwxAfterpay capture response', [
  182. 'paymentIntentId' => $paymentIntentId ?? null,
  183. 'order' => $order->increment_id ?? null,
  184. 'status' => $response->getStatusCode(),
  185. 'body' => $responseBody,
  186. ]);
  187. $result = json_decode($responseBody);
  188. return $result;
  189. }
  190. public function getToken()
  191. {
  192. $token = cache()->get($this->tokenCacheKey);
  193. if (!$token) {
  194. $client = new Client();
  195. $response = $client->request('POST', $this->tokenUrl, [
  196. 'headers' => [
  197. 'Accept' => 'application/json',
  198. 'Content-Type' => 'application/json',
  199. 'x-client-id' => $this->clientId,
  200. 'x-api-key' => $this->apikey
  201. ],
  202. 'timeout' => 30,
  203. 'verify' => false
  204. ]);
  205. $result = json_decode($response->getBody()->getContents());
  206. $token = $result->token;
  207. cache()->put($this->tokenCacheKey, $token, 20);
  208. }
  209. return $token;
  210. }
  211. //成功修改状态
  212. public function payments_webhook_payment_intent_succeeded($orderId, $transactionId)
  213. {
  214. $order = app(OrderRepository::class)->find($orderId);
  215. if (!$order) {
  216. return false;
  217. }
  218. if ($order->status != Order::STATUS_PENDING) {
  219. return false;
  220. }
  221. $order->status = Order::STATUS_PROCESSING;
  222. $order->save();
  223. if ($order->payment) {
  224. $order->payment->update([
  225. 'transaction_id' => $transactionId,
  226. ]);
  227. }
  228. }
  229. //授权成功修改状态
  230. public function payments_webhook_payment_intent_requires_capture($orderId, $transactionId)
  231. {
  232. $order = app(OrderRepository::class)->find($orderId);
  233. if (!$order) {
  234. return false;
  235. }
  236. if ($order->status != Order::STATUS_PENDING) {
  237. return false;
  238. }
  239. $order->status = Order::STATUS_PROCESSING;
  240. $order->save();
  241. if ($order->payment) {
  242. $order->payment->update([
  243. 'transaction_id' => $transactionId,
  244. ]);
  245. }
  246. }
  247. /**
  248. * 获取一个唯一的id
  249. */
  250. public function createUuid($prefix = "")
  251. {
  252. $chars = md5(uniqid(mt_rand(), true));
  253. $uuid = substr($chars, 0, 8) . '-'
  254. . substr($chars, 8, 4) . '-'
  255. . substr($chars, 12, 4) . '-'
  256. . substr($chars, 16, 4) . '-'
  257. . substr($chars, 20, 12);
  258. return $prefix . $uuid;
  259. }
  260. public function getBaseUlr()
  261. {
  262. return config('app.url');
  263. }
  264. public function getAwxAfterpayUrl()
  265. {
  266. return route('afterpay.standard.redirect');
  267. }
  268. public function checkSignature($data, $exp)
  269. {
  270. if (empty($data)) {
  271. return false;
  272. }
  273. if (hash_hmac('sha256', $data['timestamp'].$data['content'], $this->$exp) != $data['signature']) {
  274. return false;
  275. }
  276. return true;
  277. }
  278. public function getPrefix()
  279. {
  280. return $this->prefix;
  281. }
  282. /**
  283. * Get payment method image.
  284. *
  285. * @return array
  286. */
  287. public function getImage()
  288. {
  289. $url = $this->getConfigData('image');
  290. return $url ? Storage::url($url) : bagisto_asset('images/cash-on-delivery.png', 'shop');
  291. }
  292. public function isAvailable()
  293. {
  294. if (! parent::isAvailable()) {
  295. return false;
  296. }
  297. $info = $this->getOrder() ?: Cart::getCart();
  298. if ($info && $billingCountry = $info->billing_address->country ?? false) {
  299. $allowedCountries = ['AU', 'CA', 'NZ', 'GB', 'US'];
  300. return in_array($billingCountry, $allowedCountries);
  301. }
  302. return true;
  303. }
  304. }