当前位置:网站首页>PHP easywechat and applet realize long-term subscription message push
PHP easywechat and applet realize long-term subscription message push
2022-06-25 01:18:00 【PHP code】
Need to use in daily project development Push messages to read
wx.requestSubscribeMessage({
tmplIds: tempId,
success: res => {
console.log(' Tune up successfully ');
if (res[tempId[0]] === 'accept') {
console.log(' allow ')
}
if (res[tempId[0]] === 'reject') {
console.log(' Refuse ')
}
},
fail: err => {
if (err.errCode == 20004) {
console.log(' Turn off the applet main switch ')
} else {
console.log(' Subscription failed ')
}
}
});
// This is the place to obtain the distribution permission , According to official documents , According to wx.getSetting() Of withSubscriptions This parameter gets whether the user turns on the main switch of subscription message . Later, we need to get whether the user agrees to always agree to the message push . So here we set it to true .
wx.getSetting({
withSubscriptions: true, // I'm going to set it to true, Then we will return to mainSwitch
success: function(res){
// Pop up the authorization interface
if (res.subscriptionsSetting.mainSwitch) { // The user turned on the main switch of subscription message
if (res.subscriptionsSetting.itemSettings != null) { // Users agree to always keep the choice of whether to push messages , This means that the authorization of pushing messages will not be pulled up in the future
let moIdState = res.subscriptionsSetting.itemSettings[tmplIds]; // Message template agreed by the user id
if(moIdState === 'accept'){
console.log(' Received message push ');
}else if(moIdState === 'reject'){
console.log(" Reject message push ");
}else if(moIdState === 'ban'){
console.log(" Has been blocked by the background ");
}
}else {
// When the user does not click ’ Always keep the above options , Stop asking ‘ Button . Then every time I hold it here, I will pull up the authorization pop-up window
wx.showModal({
title: ' Tips ',
content:' Please authorize to open the service notice ',
showCancel: true,
success: function (ress) {
if (ress.confirm) {
wx.requestSubscribeMessage({ // Call up the message subscription interface
tmplIds: ['Bbd5Rv4R3vZO7Jh8SEKXESDXq5Vrh6jn-BRIaoOSj30'],
success (res) {
console.log(' Subscribe to news success ');
console.log(res);
},
fail (er){
console.log(" Subscribe to news Failure ");
console.log(er);
}
})
}
}
})
}
}else {
console.log(' Subscription message is not turned on ')
}
},
fail: function(error){
console.log(error);
},
})php Code
/**
* Service verification
*
* @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 = [
// Cadre training
'app_id' => $this->appId,
'secret' => $this->secret,
// Appoint API Call to return the type of the result :array(default)/collection/object/raw/ Custom class name
'response_type' => 'array',
// Log configuration
// level: The level of logging , Optional : debug/info/notice/warning/error/critical/alert/emergency
// path: Log file location ( Absolute path ), Require writable rights
'log' => [
'default' => 'dev', // Default channel, The production environment can be changed to the following prod
'channels' => [
// Test environment
'dev' => [
'driver' => 'single',
'path' => $this->projectDir . '/var/logs/weChat_dev.log',
'level' => 'debug',
],
// Production environment
'prod' => [
'driver' => 'daily',
'path' => $this->projectDir . '/var/logs/weChat_prod.log',
'level' => 'info',
],
],
],
];
return Factory::miniProgram($options);
}
/**
* Generate scene QR code
*
* @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;
}
// Save applet code to file
if ($response instanceof StreamResponse) {
$fileName = 'weChat_' . date('YmdHis');
$response->save($this->dir, $fileName);
$filePath = $this->dir . '/' . $fileName . '.jpg';
// Judge whether the QR code is saved correctly
if (!file_exists($filePath)) return '';
return $this->weChatDir . '/' . $fileName . '.jpg';
} else {
return false;
}
}
/**
* obtain AccessToken
*
* @return mixed
* @throws HttpException
* @throws InvalidArgumentException
* @throws InvalidConfigException
* @throws RuntimeException
* @throws \Psr\SimpleCache\InvalidArgumentException
*/
public function getAccessToken()
{
// obtain access token example
$accessToken = $this->app()->access_token->getToken();
// token Array token['access_token'] character string
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);
}
/**
* Service verification
*
* @return array|Collection|object|ResponseInterface|string
* @throws InvalidConfigException
*/
public function getCheckSignature()
{
$server = $this->app()->server->serve();
return $server;
}
/**
* Data decryption
*
* @param $session
* @param $iv
* @param $encryptedData
* @return array
* @throws DecryptException
*/
public function decryptData($session, $iv, $encryptedData)
{
return $this->app()->encryptor->decryptData($session, $iv, $encryptedData);
}
/**
* Subscribe to message sending
*
* @param $data
* @return array|string
* @throws \Psr\SimpleCache\InvalidArgumentException
*/
public function subscribeMessage($data)
{
try {
// Set up AccessToken solve access_token is invalid problem
$this->getTmpl()->setAccessToken($this->getAccessToken());
// Handle string length
$res = $this->characterHandle($data);
// message sending
return $this->getTmpl()->send($res);
} catch (\Exception $exception) {
return $exception->getMessage();
}
}
/**
* Character length processing
* Wechat subscription message regulations Field length cannot be greater than 20 character
*
* @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);
}边栏推荐
- 腾讯完成全面上云 打造国内最大云原生实践
- Bi SQL constraints
- Scala IO reads by lexical units and numbers
- 1. 封装自己的脚手架 2.创建代码模块
- AutoCAD - two extension modes
- Cobalt strike installation tutorial
- PHP 利用getid3 获取mp3、mp4、wav等媒体文件时长等数据
- 新手看过来,带你一次性了解“软考”
- 【直播回顾】2022腾讯云未来社区城市运营方招募会暨SaaS 2.0新品发布会!
- How much commission does CICC wealth securities open an account? Is stock account opening and trading safe and reliable?
猜你喜欢
随机推荐
Tencent has completed the comprehensive cloud launch to build the largest cloud native practice in China
新一代可级联的以太网远程I/O数据采集模块
The latest QQ wechat domain name anti red PHP program source code + forced jump to open
ImageView展示网络图片
丹麦技术大学首创将量子计算应用于能源系统潮流建模
Tencent cloud wecity Industry joint collaborative innovation to celebrate the New Year!
利用 Redis 的 sorted set 做每周热评的功能
欢迎来到联想智能大屏的新世界
天书夜读笔记——反汇编引擎xde32
Go language operators (under Lesson 8)
Scala adapter pattern
戴尔为何一直拒绝将商用本的超薄推向极致?
天书夜读笔记——深入虚函数virtual
JS Chapter 1 Summary
15. several methods of thread synchronization
ImageView shows network pictures
Convert MySQL query timestamp to date format
Library management system code source code (php+css+js+mysql) complete code source code
Contentresolver, get the SMS content
纹理增强








