首頁  >  文章  >  微信小程式  >  如何實作小程式推播範本訊息

如何實作小程式推播範本訊息

WJ
WJ原創
2020-06-10 14:24:113111瀏覽

如何實作小程式推播範本訊息

如何實作小程式推送範本訊息?

以下為開發步驟

取得使用者的openid

以取得form_id或prepay_id

取得access_token

發送範本訊息

#DEMO下載位址

重要提示

此方法為利用PHP內建curl模組發送請求,開發中都是以此方法存取微信伺服器取得數據,其中url為介面位址,params為攜帶參數,ispost為請求方式,https為憑證校驗

 public static function curl($url, $params = false, $ispost = 0, $https = 0)
    {
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8'
            )
        );
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($https) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
        }
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                if (is_array($params)) {
                    $params = http_build_query($params);
                }
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }
        $response = curl_exec($ch);
        if ($response === FALSE) {
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }

取得使用者的openid

微信小程式程式碼,建議放在app.js全域保存,方便呼叫
wx.login({
      success: function (res) {
        wx.request({
          url: "www.xxx.com",  //你的服务器接口地址
          data: {
            code:res.code  //通过wx.login获取code发送至服务器
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            that.globalData.OpenId=res.data.openid //存储openid
          }
        })
      }
    })

伺服器端PHP程式碼,我用的是laravel框架,可自行重構

public function getUserInfo(Request $request)
    {
        $code = $request->get("code"); 
        $appid="";   //小程序appid
        $secret=""; //小程序secret
        $Url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secre . '&js_code=' . $code . '&grant_type=authorization_code'; //微信官方给出的接口,利用小程序内获取的code置换openid
        $UserInfo=HttpUtils::curl($Url, $params = false, $ispost = 0, $https = 1); //上文给出的curl方法
        echo $UserInfo; //输出结果,其中包含openid
    }

取得form_id或prepay_id

本篇只做簡要介紹,留到下篇部落格微信支付講解

1.form_id為小程式內提交表單時所產生的id,當使用者在小程式內發生過提交表單行為且該表單聲明為要發範本訊息的,開發者需要向使用者提供服務時,可允許開發者向使用者在7天內推送有限條數的範本訊息(1次提交表單可下發1條,多次提交下發條數獨立,相互不影響)

2.prepay_id為小程式拉起微信支付時所產生的預付id,當使用者在小程式內完成過付款行為,可允許開發者向使用者在7天內推送有限條數的範本訊息(1次付款可下發3條,多次支付下發條數獨立,互相不影響)

取得access_token此方法為取得access_token為後續發送範本訊息提供參數,我用的是laravel框架,可自行重構

public static function access_token(){
        $appid="";   //小程序appid
        $secret=""; //小程序secret
        $Url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=". $appid."&secret=".$secret; //微信给出的获取access_token的接口
        $access_token=Cache::get("access_token");  //查询缓存中是否已存在access_token
        if($access_token==""){
            $access_token=json_decode(self::curl($Url))->{"access_token"};  //访问接口获取access_token
            Cache::put("access_token",$access_token,120); //设置缓存,过期时间2小时
        }
        return $access_token;
    }

傳送範本訊息

###發送範本訊息方法###
public static function SendMsg($data,$access_token){
        $MsgUrl="https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$access_token; //微信官方接口,需要拼接access_token
        return json_decode(self::curl($MsgUrl,$params=json_encode($data),$ispost=1,$https=1)); //访问接口,返回参数
    }
###呼叫範例###
public function test(Request $request){
        $form_id=$request->get("form_id");
        $openid=$request->get("openid");
        $access_token=WxUtils::access_token();
        $data=[
            "touser"=>$openid, //接收用户的openid
            "template_id"=>"k03-Sk5c4eNlQKrS4VqI4cKjEil7JyvcouxtKBFkVcs",  //模板id
            "page"=>"pages/index/index",//点击模板消息跳转至小程序的页面
            "form_id"=>$form_id, //可为表单提交时form_id,也可是支付产生的prepay_id
            "data"=>[
                "keyword1"=>[
                    "value"=> "五公司", //自定义参数
                    "color"=> '#173177'//自定义文字颜色
                ],
                "keyword2"=>[
                    "value"=> "保洁服务",//自定义参数
                    "color"=> '#173177'//自定义文字颜色
                ],
                "keyword3"=>[
                    "value"=> "2018年10月",//自定义参数
                    "color"=> '#173177'//自定义文字颜色
                ],
                "keyword4"=>[
                    "value"=> "已发布",//自定义参数
                    "color"=> '#173177'//自定义文字颜色
                ],
                "keyword5"=>[
                    "value"=> "请至小程序订单列表进行查看",//自定义参数
                    "color"=> '#173177'//自定义文字颜色
                ],
            ]
        ];
        $res=WxUtils::SendMsg($data,$access_token); //返回结果
    }
#######總結######1.openid取得挺簡單的,就是你的appid和secret別搞錯就行######2.access_token同上,也是別搞錯填寫的參數,嚴格按照官方給出的文檔填######3.模板訊息的data中,跳轉小程式的路由嚴格依照你小程式所寫路由填寫,跳轉pages/index/index別寫成…/index/inex#########相關推薦:######小程式教學#### ########

以上是如何實作小程式推播範本訊息的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn