Wxapp.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace app\store\model;
  3. use think\Cache;
  4. use app\common\model\Wxapp as WxappModel;
  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. * 删除wxapp缓存
  65. * @return bool
  66. */
  67. public static function deleteCache()
  68. {
  69. return Cache::rm('wxapp_' . self::$wxapp_id);
  70. }
  71. }