Yzy.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace App\Components;
  3. use App\Http\Models\Config;
  4. use Cache;
  5. use Log;
  6. class Yzy
  7. {
  8. protected static $config;
  9. protected $accessToken;
  10. function __construct()
  11. {
  12. self::$config = $this->systemConfig();
  13. $this->accessToken = $this->getAccessToken();
  14. }
  15. // 获取accessToken
  16. public function getAccessToken()
  17. {
  18. if (Cache::has('YZY_TOKEN')) {
  19. $token = Cache::get('YZY_TOKEN');
  20. if (isset($token['error'])) { // 错误兼容
  21. Cache::forget('YZY_TOKEN');
  22. } else {
  23. return Cache::get('YZY_TOKEN')['access_token'];
  24. }
  25. }
  26. $keys['kdt_id'] = self::$config['kdt_id'];
  27. $token = (new \Youzan\Open\Token(self::$config['youzan_client_id'], self::$config['youzan_client_secret']))->getToken('self', $keys);
  28. if (isset($token['error'])) {
  29. Log::info('获取有赞云支付access_token失败:' . $token['error_description']);
  30. return '';
  31. } else {
  32. Cache::put('YZY_TOKEN', $token, 10000);
  33. return $token['access_token'];
  34. }
  35. }
  36. // 生成收款二维码
  37. public function createQrCode($goodsName, $price, $orderId)
  38. {
  39. $client = new \Youzan\Open\Client($this->accessToken);
  40. $params = [
  41. 'qr_name' => $goodsName, // 商品名
  42. 'qr_price' => $price, // 单位分
  43. 'qr_source' => $orderId, // 本地订单号
  44. 'qr_type' => 'QR_TYPE_DYNAMIC'
  45. ];
  46. return $client->get('youzan.pay.qrcode.create', '3.0.0', $params);
  47. }
  48. // 通过tid获取交易信息
  49. public function getTradeByTid($tid)
  50. {
  51. $client = new \Youzan\Open\Client($this->accessToken);
  52. return $client->post('youzan.trade.get', '3.0.0', ['tid' => $tid]);
  53. }
  54. // 系统配置
  55. private function systemConfig()
  56. {
  57. $config = Config::query()->get();
  58. $data = [];
  59. foreach ($config as $vo) {
  60. $data[$vo->name] = $vo->value;
  61. }
  62. return $data;
  63. }
  64. }