当前位置:网站首页>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);
}边栏推荐
- Library management system code source code (php+css+js+mysql) complete code source code
- Using bindservice method to pause music playing
- Start service 11111
- Leetcode 1248. Statistics of "graceful subarray" (harm, suddenly found that it can only enumerate violently)
- 图书馆管理系统代码源码(php+css+js+mysql) 完整的代码源码
- Mobile security tool apktool
- Mysql database Chapter 1 Summary
- 利用 Redis 的 sorted set 做每周热评的功能
- Text editor of QT project practice ---------- episode 8
- 汇编语言(3)16位汇编基础框架与加减循环
猜你喜欢

粉丝福利,JVM 手册(包含 PDF)

I 刷题 I — 复制带随机指针的链表

Programmer: did you spend all your savings to buy a house in Shenzhen? Or return to Changsha to live a "surplus" life?

Rich text tables, lists, pictures

Zuckerberg demonstrated four VR head display prototypes, and meta revealed the "family" of metauniverse
![[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

Première application de l'informatique quantique à la modélisation des flux de puissance dans les systèmes énergétiques à l'Université technique danoise

Library management system code source code (php+css+js+mysql) complete code source code

2022年危险化学品经营单位安全管理人员考试试题及模拟考试

2022安全员-C证考试模拟100题及在线模拟考试
随机推荐
QT electronic clock
Mobile security tool jar
Programmer: did you spend all your savings to buy a house in Shenzhen? Or return to Changsha to live a "surplus" life?
Mysql database Chapter 1 Summary
The optimism about technology is making Dell achieve more than expected
Mobile security tool apktool
扎克伯格上手演示四款VR头显原型机,Meta透露元宇宙「家底」
Super detailed description and derivation of convolution and deconvolution (deconvolution is also called transpose convolution and fractional step convolution)
联想童夫尧:11倍于大势,我们一路攻城拔寨
Deploy a production cluster using Loki microservice pattern
Novice, let me show you the "soft test" at one time
图书馆管理系统代码源码(php+css+js+mysql) 完整的代码源码
Leetcode 1248. Statistics of "graceful subarray" (harm, suddenly found that it can only enumerate violently)
Bi SQL alias
15. several methods of thread synchronization
我想问一下兴业证券怎么开户?通过链接办理股票开户安全吗
Distinguish between i++ and ++i seconds
[redis realizes seckill service ②] solution to oversold problem
VB 学习笔记
Activity lifecycle