当前位置:网站首页>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);
}边栏推荐
- bindservice方法实现音乐播放暂停
- Danish Technical University pioneered the application of quantum computing to power flow modeling of energy system
- 【直播回顾】2022腾讯云未来社区城市运营方招募会暨SaaS 2.0新品发布会!
- [untitled]
- 腾讯云WeCity解决方案
- Lenovo tongfuyao: 11 times the general trend, we attacked the city and pulled out the stronghold all the way
- What to learn in VB [easy to understand]
- Scala object blending trait
- 108页(4万字)未来公寓智能化设计平台项目方案建议书2022版
- yasea apk 下载 镜像
猜你喜欢
![[redis realizes seckill business ③] specific implementation of optimistic lock for oversold problem](/img/01/5ec4e5dae1748dce3d5dee33a24b0b.png)
[redis realizes seckill business ③] specific implementation of optimistic lock for oversold problem

Bi-sql - join

Text editor of QT project practice ---------- episode 11

图书馆管理系统代码源码(php+css+js+mysql) 完整的代码源码

Text editor for QT project practice - Episode 12
![[redis realizes seckill service ②] solution to oversold problem](/img/b6/3073def06a56565894c28e49767e3e.png)
[redis realizes seckill service ②] solution to oversold problem

2022 melting welding and thermal cutting recurrent training question bank simulated examination platform operation

Mobile security tool jar

4年工作经验,多线程间的5种通信方式都说不出来,你敢信?

51单片机多机通信
随机推荐
卷积与转置卷积
Programmer: did you spend all your savings to buy a house in Shenzhen? Or return to Changsha to live a "surplus" life?
Mobile security tool -dex2jar
Scala IO reads by lexical units and numbers
归并排序求逆序数
网上开户选哪个证券公司?网上开户安全么?
yasea apk 下载 镜像
vb学习什么[通俗易懂]
EVM Brief
归并排序模板 & 理解
汇编语言(2)基础知识-debug
Golang example renewal lock: redis+channel+sync Mutex
Bi-sql - join
2022 crane driver (limited to bridge crane) examination question bank simulated examination platform operation
智能合约安全审计入门篇 —— delegatecall (2)
Bi SQL alias
Bi-sql like
Text border format and text block of rich text
指南针炒股软件怎么样?安全吗?
Using macro code to generate handwriting automatically in word or WPS