php 发送微信订阅消息

微信接口文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html

php代码:

public function send_template()
{
    //用户msg表id
    $id = input('id');
    //获取模板ID
    $msg_info = Db::name('template_msg')->where(['id' => $id])->find(); 

	//获取模板内容
    $info = Db::name('template')->where(['template_id' => $msg_info['tmpl_id']])->find();
    
    // 页面跳转
    $page = 'surebetter_shop/pages/index/index';
    
    // 获取acceess_token
    $appid = '';
    $appscert = '';
    $access_token = access_token($appid, $appscert);
    if (isset($access_token['errcode'])) {
        ajaxReturn(['status' => -1, 'msg' => '获取access_token失败', 'data' => $access_token]);
    }

    //获取获取消息的用户的openid
    $openid = '';

	//发送内容格式
    $data = [
        'touser' => $openid['openid'],
        'template_id' => $msg_info['tmpl_id'],
        'page' => $page,
        'data' => json_decode($info['data']),
    ];
	
	//发送
    $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token;
    $result = httpRequest($url, 'POST', json_encode($data));
    $result = json_decode($result, true);

	//access_token过期处理
    if ($result['errcode'] == 40001) {
    	//access_token设为空,过期时间归零
        Db::name('config')->where(['name' => 'access_token'])->update(['value' => '']);
        Db::name('config')->where(['name' => 'expires_time'])->update(['value' => 0]);
		
		//重新发送
		$access_token = access_token($appid, $appscert);
		$url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token;
        $result = httpRequest($url, 'POST', json_encode($data));
        $result = json_decode($result, true);
    }

    //结果处理
    if (isset($result['errcode']) && $result['errcode'] == 0) {		//成功
        Db::name('template_msg')->where(['id' => $id, 'tmpl_id' => $msg_info['tmpl_id']])->update(['is_use' => 1, 'status' => 1, 'errcode' => $result['errcode'], 'errmsg' => $result['errmsg']]);

        ajaxReturn(['status' => 1, 'msg' => '发送成功', 'data' => $result]);
    } else {
		//失败
        Db::name('template_msg')->where(['id' => $id])->update(['is_use' => 1, 'status' => 2, 'errcode' => $result['errcode'], 'errmsg' => $result['errmsg']]);
        $msg = '发送失败';
        if ($result['errcode'] == 43101) {
            $msg .= ',用户拒绝接受消息';
        } elseif ($result['errcode'] == 47003) {
            $msg .= ',模板参数不准确,可能为空或者不满足规则';
        } elseif ($result['errcode'] == 40003) {
            $msg .= ',openid为空或者不正确';
        }

        ajaxReturn(['status' => 0, 'msg' => $msg, 'data' => $result]);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值