QrcodeService.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace addons\Wechat\services;
  3. use Yii;
  4. use common\components\Service;
  5. use addons\Wechat\common\models\Qrcode;
  6. use addons\Wechat\common\enums\QrcodeModelTypeEnum;
  7. /**
  8. * Class QrcodeService
  9. * @package addons\Wechat\services
  10. * @author jianyan74 <751393839@qq.com>
  11. */
  12. class QrcodeService extends Service
  13. {
  14. /**
  15. * @param array $where
  16. * @return array|null|\yii\db\ActiveRecord|Qrcode
  17. */
  18. public function findByWhere(array $where = [])
  19. {
  20. return Qrcode::find()
  21. ->filterWhere($where)
  22. ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
  23. ->orderBy('created_at desc')
  24. ->one();
  25. }
  26. /**
  27. * 返回场景ID
  28. *
  29. * @return int|mixed
  30. */
  31. public function getSceneId()
  32. {
  33. $qrCode = Qrcode::find()
  34. ->where(['model_type' => QrcodeModelTypeEnum::TEM])
  35. ->andWhere(['merchant_id' => Yii::$app->services->merchant->getAutoId()])
  36. ->orderBy('created_at desc')
  37. ->one();
  38. return $qrCode ? $qrCode->scene_id + 1 : 10001;
  39. }
  40. /**
  41. * @param Qrcode $model
  42. */
  43. public function syncCreateByData($data)
  44. {
  45. $model = new Qrcode();
  46. $model = $model->loadDefaultValues();
  47. $model->attributes = $data;
  48. return $this->syncCreate($model);
  49. }
  50. /**
  51. * @param Qrcode $model
  52. */
  53. public function syncCreate(Qrcode $model)
  54. {
  55. if ($model->model_type == QrcodeModelTypeEnum::TEM) {
  56. $scene_id = $this->getSceneId();
  57. $result = Yii::$app->wechat->app->qrcode->temporary($scene_id, $model->expire_seconds);
  58. $model->scene_id = $scene_id;
  59. $model->expire_seconds = $result['expire_seconds']; // 有效秒数
  60. } else {
  61. $result = Yii::$app->wechat->app->qrcode->forever($model->scene_str);
  62. }
  63. $model->ticket = $result['ticket'];
  64. $model->type = 'scene';
  65. $model->url = $result['url']; // 二维码图片解析后的地址,开发者可根据该地址自行生成需要的二维码图片
  66. return $model;
  67. }
  68. }
粤ICP备19079148号