ThinkPHP 微信授权web网页 公众号推送模版消息

申请公众平台 和 公众号 各种参数填写完成!!! 我这里主要讲的是代码
第一步:前端代码

//这里的代码 对应下面的 html 代码 
public function index()
    {
        $id = $this->request->request('id');
        $userinfo =  Db::name('user')->field('id,wx_nickname,wx_head_image,openid')->where('id',$id)->find();
        if($userinfo){
            if($userinfo['openid'] == ''){
            	// 未授权
                $userinfo['is'] = 0;
            }else{
            	//已授权
                $userinfo['is'] = 1;
            }
            $this->view->assign("userinfo", $userinfo);
            session('user_info_id',$userinfo['id']);
            return $this->view->fetch();
        }else{
            echo '信息错误';exit;
        }
    }
<!--
 * @s: ========{================================================>
 * @version: 1.1.1
 * @Name: 文件:
 * @Author: Fcy
 * @Date: 2022-10-15 15:19:09
 * @FilePath: application/api/view/index/index.html
 * @E: ========{================================================>
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="__CDN__/assets/css/flex.css">
    <link rel="stylesheet" href="__CDN__/assets/css/indexs.css">
    <title>授权通知</title>
</head>
<body >
    <div class="container">
        
        <div class="n_t"><p>接收通知</p></div>
        
        <div class="sms">
            {if $userinfo['is'] == 0}
                通过微信公众号消息接受消息通知
            {/if}
            {if $userinfo['is'] == 1}
                通过微信公众号模板消息接收管理员派单的通知
            {/if}
        </div>
        

        <div class="flex-row flex-item-center user_info" id="user">
            {if $userinfo['is'] == 1}
                <div>授权用户:</div>
                <div class="flex-row flex-item-center">
                    <div class="head_image flex-row flex-item-center" >
                        <img id="images" src="{$userinfo['wx_head_image'] ? $userinfo['wx_head_image']: '__CDN__/assets/img/avatar.png'}" alt="" srcset=""/>
                    </div>
                    <div class="flex-row flex-item-center nickname">
                        <p id="nk">
                            {$userinfo['wx_nickname']}
                        </p>
                    </div>
                </div>
            {/if}
        </div>
            {if $userinfo['is'] == 0}
                <div class="authorization" onclick="authorization()">
                    <text >去授权</text>
                </div>
            {/if}
            {if $userinfo['is'] == 1}
            <div class="authorization" onclick="authorization()">
                <text >重新授权</text>
            </div>
            {/if}
        <input type="hidden" value="{$userinfo['id']|htmlentities}" id="user_id" name="id">
    </div>
    <script src="__CDN__/assets/js/jquery/jquery3.3.1.js"></script>
    <script>
        function authorization()
        {
            var appid = '这里写你的appID';
            //这里写你的回调地址 也就是获取到code 后台换取 openID 的接口 不要加任何参数
            //这里文档中有交代 授权后重定向的回调链接地址, 请使用 urlEncode 对链接进行处理
            //原本地址 http://www.baidu.com/api/index/getOpenId 
            //要改成 http%3A%2F%2Fbaidu.com%2Fapi%2Findex%2FgetOpenId 切记 
            var redirect_uri = 'http%3A%2F%2Fbaidu.com%2Fapi%2Findex%2FgetOpenId';//示例
            window.location.href=`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
        }
    </script>
</body>
</html>

在这里插入图片描述

第二步。
后端 获取 openID的方法

public function getOpenId()
    {
        $code = $this->request->get('code');
        //第一 根据code 获取openid
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->business_appid&secret=$this->business_secret&code=$code&grant_type=authorization_code";
        $data = file_get_contents($url);
        $arr = json_decode($data, true);
        if (isset($arr['openid'])) {
            $access_token = $arr['access_token'];
            $openid = $arr['openid'];
            //获取用户信息
            $getUserInfoUrl ="https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
            $userInfoData = file_get_contents($getUserInfoUrl);
            $userInfoArr = json_decode($userInfoData, true);
            if(session('user_info_id')){
                $isUser = Db::name('user')->where(['openid'=>$userInfoArr['openid'],'id'=>session('user_info_id')])->find();
                if($isUser){
                    $this->error(__('No rows were updated'));
                }
                Db::startTrans();
                try{
                    $user = Db::name('user')->where('id',session('user_info_id'))->update([
                        'openid' => $userInfoArr['openid'],
                        'wx_nickname' => $userInfoArr['nickname'],
                        'wx_head_image' => $userInfoArr['headimgurl'],
                        'openid' => $userInfoArr['openid'],
                        'updatetime' => time()
                    ]);
                    Db::commit();
                }catch(Exception $e){
                    Db::rollback();
                    $this->error(__($e->getMessage()));
                }
                if ($user) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
        } else {
            $this->error(__('No rows were updated'));
        }
    }

到这里 就授权成功了
在这里插入图片描述

第三发送模版消息
我是用的EasyWeChat.模版消息
在这里插入图片描述

模板ID xxxxxxxxxx
开发者调用模板消息接口时需提供模板ID
标题
xxxxx标题
详细内容
{{first.DATA}}.    
{{keyword1.DATA}}
{{keyword2.DATA}}
{{remark.DATA}}
在发送时,需要将内容中的参数({{.DATA}}内为参数)赋值替换为需要的信息
use EasyWeChat\Factory;

public function send()
    {
        $openid = '这是用户的openid';
        $template_id = '这是申请的模版ID';
        
        $data = [
            'first'=> '你好,您有一个运输订单取消了,请及时确认!',
            'keyword1'=> 'keyword1',
            'keyword2'=> 'keyword2',
            'remark'=> '订单已取消,请知悉!'//备注
        ];
        $res = $this->template($openid,$template_id,$data);
        print_r($res);
    }
    //发送微信模版消息
    public function template($openid,$template_id,$data,$url='',$miniprogram=['appid'=>'','pagepath'=>''])
    {
        $config = [
            'app_id' => '',
            'secret' => '',
            // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];
        $app = Factory::officialAccount($config);
        return $app->template_message->send([
            'touser' => $openid,
            'template_id' => $template_id,
            'url' => $url,
            'miniprogram' => $miniprogram,
            'data' => $data,
        ]);
    }

在这里插入图片描述
到这 就完成了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

weixin_45285275

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

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

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

打赏作者

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

抵扣说明:

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

余额充值