Yzy.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace App\Components;
  3. use Cache;
  4. use Log;
  5. class Yzy
  6. {
  7. protected static $systemConfig;
  8. protected static $accessToken;
  9. function __construct()
  10. {
  11. self::$systemConfig = Helpers::systemConfig();
  12. self::$accessToken = $this->getAccessToken();
  13. }
  14. // 获取accessToken
  15. public function getAccessToken()
  16. {
  17. if (Cache::has('YZY_TOKEN')) {
  18. $token = Cache::get('YZY_TOKEN');
  19. if (!isset($token['error'])) {
  20. return Cache::get('YZY_TOKEN')['access_token'];
  21. }
  22. Cache::forget('YZY_TOKEN');
  23. }
  24. $token = (new \Youzan\Open\Token(self::$systemConfig['youzan_client_id'], self::$systemConfig['youzan_client_secret']))->getToken('self', ['kdt_id' => self::$systemConfig['kdt_id']]);
  25. if (isset($token['error'])) {
  26. Log::info('获取有赞云支付access_token失败:' . $token['error_description']);
  27. return '';
  28. } else {
  29. Cache::put('YZY_TOKEN', $token, 180);
  30. return $token['access_token'];
  31. }
  32. }
  33. // 生成收款二维码
  34. public function createQrCode($goodsName, $price, $orderSn)
  35. {
  36. $client = new \Youzan\Open\Client(self::$accessToken);
  37. $params = [
  38. 'qr_name' => $goodsName, // 商品名
  39. 'qr_price' => $price, // 单位分
  40. 'qr_source' => $orderSn, // 本地订单号
  41. 'qr_type' => 'QR_TYPE_DYNAMIC'
  42. ];
  43. return $client->get('youzan.pay.qrcode.create', '3.0.0', $params);
  44. }
  45. // 通过tid获取交易信息
  46. public function getTradeByTid($tid)
  47. {
  48. $client = new \Youzan\Open\Client(self::$accessToken);
  49. return $client->post('youzan.trade.get', '4.0.0', ['tid' => $tid]);
  50. }
  51. // 通过二维码ID获取已支付的交易信息
  52. public function getTradeByQrId($qr_id)
  53. {
  54. $client = new \Youzan\Open\Client(self::$accessToken);
  55. return $client->post('youzan.trades.qr.get', '3.0.0', ['qr_id' => $qr_id, 'status' => 'TRADE_RECEIVED']);
  56. }
  57. }