PHP微信公众号(微信小程序)模板消息推送

/**
 * 补货订单通知
 */
public function orderStockout($store_id)
{
    $user = new \app\admin\model\User();
    $user_info = $user->where('store_id',$store_id)->find();
    if(!$user_info){
        return ['code'=>0,'message'=>'商家不存在'];
    }
    if(!$user_info['openid']){
        return ['code'=>0,'message'=>'openid未获取到,请先绑定微信账号'];
    }
    //获取商品
    $where = [
        's.uid' => $store_id,
        's.is_integral' => 0,
        's.is_stock' => 0,
    ];
    $field = 's.id,g.name,s.inventory,s.stock_num';
    $sproduct = new Product();
    $result =  $sproduct->alias('s')
        ->join('goods_product g','g.id=s.product_id','left')
        ->where($where)
        ->field($field)
        ->select();
    if(!$result){
        return ['code'=>0,'message'=>'暂无商品需要补货'];
    }
    $str = '';
    $ids = [];
    $number = 0;
    foreach($result as $ka=>$va){
        if($va['inventory'] <= $va['stock_num']){
            $str .= $va['name'].',';
            $ids[] = $va['id'];
            if($number == 0){
                $number = $va['inventory'];
            }
        }
    }
    //如果到达预警的商品数量没有
    if(count($ids) <= 0){
        return true;
    }
    //更新达到预警的商品状态
    $sproduct::where(['id'=>['in',$ids]])->update(['is_stock'=>1]);

    $data = array(
        'first' => array(
            'value'=> '您好,您有商品库存不足',
            'color'=>''
        ),
        'keyword1'=>array(
            'value'=>implode(',',$ids),
            'color'=>''
        ),
        'keyword2'=>array(
            'value'=> $str,
            'color'=>''
        ),
        'keyword3'=>array(
            'value'=> $number,
            'color'=>''
        ),
        'remark'    => array(
            'value'=>'感谢您的使用',
            'color'=>''
        ),
    );

    $url = '跳转页面';
    $template_id = '微信模板消息id';
    return $this->sendWechatMessage($user_info['openid'],$template_id,$data,$url);
}

/**
 * 发送微信模板消息
 * @param $order_id
 * @param $template
 * @return false|string|\think\response\Json
 */
public function sendWechatMessage($openid,$template_id,$data,$url)
{
    $data = array(
        "touser"        =>  $openid,        //openid
        "template_id"   =>  $template_id,             //模板id
        "url"           =>  $url,
        "data"          =>  $data      //模板数据
    );
    //下单用户发送
    $access_token = $this->access_token();
    if ($access_token == 400){
        return ['code'=>0,'message'=>'获取access_token失败'];
    }
    $urls = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
    $result = $this->http_post_json($urls,json_encode($data));//发送请求
    if($result[0] == 200){
        return ['code'=>1,'data'=>'推送成功'];
    }
    return ['code'=>0,'message'=>$result[1]['errmsg']];
}


public function http_post_json($url, $jsonStr)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($jsonStr)
        )
    );
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return [$httpCode,$response];
    // return json_encode(array($httpCode, $response),true);
    //"[200,"{\"errcode\":0,\"errmsg\":\"ok\",\"msgid\":2696398438942572550}"]"
}

//获取access_token
public function access_token(){
    $appId = Config::get('wechat_config.appid');
    $appSecret = Config::get('wechat_config.secret');
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL,$url); //要访问的地址
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//跳过证书验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
    $data = json_decode(curl_exec($ch),true);
    if(curl_errno($ch)){
        var_dump(curl_error($ch)); //若错误打印错误信息
    }
    curl_close($ch);//关闭curl
    return $data['access_token'];
}

逻辑部分可以根据具体的需求自己更改,变量格式是会根据选择用户模板而变,模板有几个变量,就写几个keyword ,小程序的话和这个大差不差,基本上就是调整一下参数就可以继续使用了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奥特曼想做个好人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值