Wxapp.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. namespace app\store\model;
  3. use app\common\model\Wxapp as WxappModel;
  4. use think\Cache;
  5. /**
  6. * 微信小程序模型
  7. * Class Wxapp
  8. * @package app\store\model
  9. */
  10. class Wxapp extends WxappModel
  11. {
  12. /**
  13. * 更新小程序设置
  14. * @param $data
  15. * @return bool
  16. * @throws \think\exception\PDOException
  17. */
  18. public function edit($data)
  19. {
  20. $this->startTrans();
  21. try {
  22. // 删除wxapp缓存
  23. self::deleteCache();
  24. // 写入微信支付证书文件
  25. $this->writeCertPemFiles($data['cert_pem'], $data['key_pem']);
  26. // 更新小程序设置
  27. $this->allowField(true)->save($data);
  28. $this->commit();
  29. return true;
  30. } catch (\Exception $e) {
  31. $this->error = $e->getMessage();
  32. $this->rollback();
  33. return false;
  34. }
  35. }
  36. /**
  37. * 写入cert证书文件
  38. * @param string $cert_pem
  39. * @param string $key_pem
  40. * @return bool
  41. */
  42. private function writeCertPemFiles($cert_pem = '', $key_pem = '')
  43. {
  44. if (empty($cert_pem) || empty($key_pem)) {
  45. return false;
  46. }
  47. // 证书目录
  48. $filePath = APP_PATH . 'common/library/wechat/cert/' . self::$wxapp_id . '/';
  49. // 目录不存在则自动创建
  50. if (!is_dir($filePath)) {
  51. mkdir($filePath, 0755, true);
  52. }
  53. // 写入cert.pem文件
  54. if (!empty($cert_pem)) {
  55. file_put_contents($filePath . 'cert.pem', $cert_pem);
  56. }
  57. // 写入key.pem文件
  58. if (!empty($key_pem)) {
  59. file_put_contents($filePath . 'key.pem', $key_pem);
  60. }
  61. return true;
  62. }
  63. /**
  64. * 记录图片信息
  65. * @param $wxapp_id
  66. * @param $oldFileId
  67. * @param $newFileName
  68. * @param $fromType
  69. * @return int|mixed
  70. */
  71. private function uploadImage($wxapp_id, $oldFileId, $newFileName, $fromType)
  72. {
  73. // $UploadFile = new UploadFile;
  74. $UploadFileUsed = new UploadFileUsed;
  75. if ($oldFileId > 0) {
  76. // 获取原图片path
  77. $oldFileName = UploadFile::getFileName($oldFileId);
  78. // 新文件与原来路径一致, 代表用户未修改, 不做更新
  79. if ($newFileName === $oldFileName)
  80. return $oldFileId;
  81. // 删除原文件使用记录
  82. $UploadFileUsed->remove('service', $oldFileId);
  83. }
  84. // 删除图片
  85. if (empty($newFileName)) return 0;
  86. // 查询新文件file_id
  87. $fileId = UploadFile::getFildIdByName($newFileName);
  88. // 添加文件使用记录
  89. $UploadFileUsed->add([
  90. 'file_id' => $fileId,
  91. 'wxapp_id' => $wxapp_id,
  92. 'from_type' => $fromType
  93. ]);
  94. return $fileId;
  95. }
  96. /**
  97. * 删除wxapp缓存
  98. * @return bool
  99. */
  100. public static function deleteCache()
  101. {
  102. return Cache::rm('wxapp_' . self::$wxapp_id);
  103. }
  104. }