Wxapp.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\store\model;
  13. use think\facade\Cache;
  14. use app\common\model\Wxapp as WxappModel;
  15. /**
  16. * 微信小程序模型
  17. * Class Wxapp
  18. * @package app\store\model
  19. */
  20. class Wxapp extends WxappModel
  21. {
  22. /**
  23. * 更新小程序设置
  24. * @param $data
  25. * @return mixed
  26. */
  27. public function edit(array $data)
  28. {
  29. // 默认数据
  30. $data['cert_pem'] = $data['cert_pem'] ?? '';
  31. $data['key_pem'] = $data['key_pem'] ?? '';
  32. // 事务处理
  33. return $this->transaction(function () use ($data) {
  34. // 删除wxapp缓存
  35. self::deleteCache();
  36. // 写入微信支付证书文件
  37. $this->writeCertPemFiles($data['cert_pem'], $data['key_pem']);
  38. // 更新小程序设置
  39. return $this->save($data);
  40. });
  41. }
  42. /**
  43. * 写入cert证书文件
  44. * @param string|null $certPem
  45. * @param string|null $keyPem
  46. * @return bool
  47. */
  48. private function writeCertPemFiles(string $certPem = '', string $keyPem = '')
  49. {
  50. if (empty($certPem) && empty($keyPem)) {
  51. return false;
  52. }
  53. // 证书目录
  54. $filePath = base_path() . 'common/library/wechat/cert/' . self::$storeId . '/';
  55. // 目录不存在则自动创建
  56. if (!is_dir($filePath)) {
  57. mkdir($filePath, 0755, true);
  58. }
  59. // 写入cert.pem文件
  60. if (!empty($certPem)) {
  61. file_put_contents($filePath . 'cert.pem', $certPem);
  62. }
  63. // 写入key.pem文件
  64. if (!empty($keyPem)) {
  65. file_put_contents($filePath . 'key.pem', $keyPem);
  66. }
  67. return true;
  68. }
  69. /**
  70. * 删除wxapp缓存
  71. * @return bool
  72. */
  73. public static function deleteCache()
  74. {
  75. return Cache::delete('wxapp_' . self::$storeId);
  76. }
  77. }