当前位置:网站首页>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);
}边栏推荐
猜你喜欢

2022 crane driver (limited to bridge crane) examination question bank simulated examination platform operation

丹麦技术大学首创将量子计算应用于能源系统潮流建模

Bi-sql select into

Bi-sql between

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

Scala IO read by line

How to store dataframe data in pandas into MySQL

Syntax highlighting of rich text

Ideas and examples of divide and conquer

LLVM TargetPassConfig
随机推荐
粉丝福利,JVM 手册(包含 PDF)
Ecological escort cloud service providers wave "Intel flag"
Scala IO read by character
天书夜读笔记——内存分页机制
ImageView展示网络图片
云开发技术峰会·公益编程挑战赛【火热报名中】!
1. 封装自己的脚手架 2.创建代码模块
Use redis' sorted set to make weekly hot Reviews
Scala adapter pattern
lnmp环境安装ffmpeg,并在Yii2中使用
Tencent cloud wecity solution
51 single chip microcomputer multi computer communication
Transform BeanUtils to achieve list data copy gracefully
MySQL common basic statements (collation)
[live review] 2022 Tencent cloud future community city operator recruitment conference and SaaS 2.0 new product launch!
Bi-sql create
[untitled]
4年工作经验,多线程间的5种通信方式都说不出来,你敢信?
Novice, let me show you the "soft test" at one time
Ideas and examples of divide and conquer