当前位置:网站首页>php easywechat 和 小程序 实现 长久订阅消息推送

php easywechat 和 小程序 实现 长久订阅消息推送

2022-06-24 20:35:00 PHP代码

在日常项目开发中需要使用 推送消息来进行阅读

 

wx.requestSubscribeMessage({
   tmplIds: tempId,
   success: res => {
     console.log('调起成功');
     if (res[tempId[0]] === 'accept') {
         console.log('允许')
     }
     if (res[tempId[0]] === 'reject') {
       console.log('拒绝')
     }
   },
   fail: err => {
     if (err.errCode == 20004) {
       console.log('关闭小程序主开关')
     } else {
       console.log('订阅失败')
     }
   }
 });

 

// 这里是获取下发权限地方,根据官方文档,可以根据  wx.getSetting() 的 withSubscriptions   这个参数获取用户是否打开订阅消息总开关。后面我们需要获取用户是否同意总是同意消息推送。所以这里要给它设置为true 。
      wx.getSetting({
        withSubscriptions: true,   //  这里设置为true,下面才会返回mainSwitch
        success: function(res){   
        
          // 调起授权界面弹窗
          if (res.subscriptionsSetting.mainSwitch) {  // 用户打开了订阅消息总开关
            if (res.subscriptionsSetting.itemSettings != null) {   // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
              let moIdState = res.subscriptionsSetting.itemSettings[tmplIds];  // 用户同意的消息模板id
              if(moIdState === 'accept'){   
                console.log('接受了消息推送');

              }else if(moIdState === 'reject'){
                console.log("拒绝消息推送");

              }else if(moIdState === 'ban'){
                console.log("已被后台封禁");

              }
            }else {
              // 当用户没有点击 ’总是保持以上选择,不再询问‘  按钮。那每次执到这都会拉起授权弹窗
              wx.showModal({
                title: '提示',
                content:'请授权开通服务通知',
                showCancel: true,
                success: function (ress) {
                  if (ress.confirm) {  
                    wx.requestSubscribeMessage({   // 调起消息订阅界面
                      tmplIds: ['Bbd5Rv4R3vZO7Jh8SEKXESDXq5Vrh6jn-BRIaoOSj30'],
                      success (res) { 
                        console.log('订阅消息 成功 ');
                        console.log(res);
                      },
                      fail (er){
                        console.log("订阅消息 失败 ");
                        console.log(er);
                      }
                    })     
                          
                  }
                }
              })
            }

          }else {
            console.log('订阅消息未开启')
          }      
        },
        fail: function(error){
          console.log(error);
        },
      })

php代码

    /**
     * 服务校验
     *
     * @return array|Collection|object|ResponseInterface|string
     * @throws InvalidConfigException
     */
    public function getCheckSignature()
    {
        $server = $this->app()->server->serve();

        return $server;
    }
/**
     * app
     *
     * @return Application
     */
    public function app()
    {
        $options = [
            // 干部培训
            'app_id' => $this->appId,
            'secret' => $this->secret,

            // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            // 日志配置
            // level: 日志级别, 可选为: debug/info/notice/warning/error/critical/alert/emergency
            // path:日志文件位置(绝对路径),要求可写权
            'log' => [
                'default' => 'dev', // 默认使用的 channel,生产环境可以改为下面的 prod
                'channels' => [
                    // 测试环境
                    'dev' => [
                        'driver' => 'single',
                        'path' => $this->projectDir . '/var/logs/weChat_dev.log',
                        'level' => 'debug',
                    ],
                    // 生产环境
                    'prod' => [
                        'driver' => 'daily',
                        'path' => $this->projectDir . '/var/logs/weChat_prod.log',
                        'level' => 'info',
                    ],
                ],
            ],
        ];

        return Factory::miniProgram($options);
    }

    /**
     * 生成场景二维码
     *
     * @param $sceneValue
     * @param  $path
     * @return bool
     * @throws InvalidArgumentException
     * @throws RuntimeException
     */
    public function generateQrCode($sceneValue, $path)
    {
        try {
            $response = $this->app()->app_code->getUnlimit($sceneValue, ['page' => $path]);
        } catch (\Exception $e) {
            return false;
        }

        // 保存小程序码到文件
        if ($response instanceof StreamResponse) {
            $fileName = 'weChat_' . date('YmdHis');
            $response->save($this->dir, $fileName);

            $filePath = $this->dir . '/' . $fileName . '.jpg';
            // 判断二维码是否正确保存
            if (!file_exists($filePath)) return '';
            return $this->weChatDir . '/' . $fileName . '.jpg';
        } else {
            return false;
        }
    }

    /**
     * 获取AccessToken
     *
     * @return mixed
     * @throws HttpException
     * @throws InvalidArgumentException
     * @throws InvalidConfigException
     * @throws RuntimeException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function getAccessToken()
    {
        // 获取 access token 实例
        $accessToken = $this->app()->access_token->getToken();
        // token 数组 token['access_token'] 字符串
        return $accessToken['access_token'];
    }

    /**
     * sessionKey
     *
     * @param $code
     * @return array|Collection|object|ResponseInterface|string
     * @throws InvalidConfigException
     */
    public function code2Session($code)
    {
        return $this->app()->auth->session($code);
    }

    /**
     * 服务校验
     *
     * @return array|Collection|object|ResponseInterface|string
     * @throws InvalidConfigException
     */
    public function getCheckSignature()
    {
        $server = $this->app()->server->serve();

        return $server;
    }
    /**
     * 数据解密
     *
     * @param $session
     * @param $iv
     * @param $encryptedData
     * @return array
     * @throws DecryptException
     */
    public function decryptData($session, $iv, $encryptedData)
    {
        return $this->app()->encryptor->decryptData($session, $iv, $encryptedData);
    }

    /**
     * 订阅消息发送
     *
     * @param $data
     * @return array|string
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function subscribeMessage($data)
    {
        try {
            // 设置 AccessToken 解决 access_token is invalid 问题
            $this->getTmpl()->setAccessToken($this->getAccessToken());
            // 处理字符串长度
            $res = $this->characterHandle($data);
            // 消息发送
            return $this->getTmpl()->send($res);
        } catch (\Exception $exception) {
            return $exception->getMessage();
        }
    }

    /**
     * 字符长度处理
     * 微信订阅消息规定 字段长度不能大于20字符
     *
     * @param $data
     * @return array
     */
    public function characterHandle($data)
    {
        $res = [];
        foreach ($data as $key => $value) {
            if ($key == 'data') {
                foreach ($value as $k => $v) {
                    $res[$key][$k] = [
                        'value' => mb_strlen($v['value']) >= 20 ? mb_substr($v['value'], 0, 15) . '...' : $v['value']
                    ];
                }
            } else {
                $res[$key] = $value;
            }
        }
        return $res;
    }

    /**
     * tmpl
     *
     * @return Newtmpl
     */
    private function getTmpl()
    {
        $config = [
            'token' => '',
            'appid' => $this->appId,
            'appsecret' => $this->secret,
            'encodingaeskey' => '',
        ];

        return new Newtmpl($config);
    }

原网站

版权声明
本文为[PHP代码]所创,转载请带上原文链接,感谢
https://blog.csdn.net/vcit102/article/details/125444228