小程式生成帶推薦碼(場景id)的二維碼
阿新 • • 發佈:2020-08-17
<?php namespace Business\Controller; use Think\Hook; /** * 小程式碼[帶推薦碼/場景id] * @author 戈丫汝<[email protected]> */ class XcxqrcodeController{ protected $appid = ''; protected $secret = ''; protected $url = ""; protected $access_tokens = ""; public function __construct(){ $mpid = $_GET['mpid']; $appid = M('test')->where(['mpid'=>$mpid,'name'=>'xcx_appid'])->getField('value'); $appsecret = M('test')->where(['mpid'=>$mpid,'name'=>'xcx_appsecret'])->getField('value'); $this->appid = $appid; $this->secret = $appsecret; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->secret . ""; $result = $this->httpRequest($url); $access_tokens = json_decode($result, true); $this->access_tokens = $access_tokens['access_token']; } //列印二維碼顯示 [[入口地址]] public function Follow(){ $scene_str = $_GET['id'];//場景id/推薦碼 $mpid = $_GET['mpid']; $rs = $this->getTemporaryQrcode($mpid,$this->access_tokens, $scene_str); echo $rs; } //生成二維碼 public function getTemporaryQrcode($mpid,$access_tokens,$scene_str=''){ //首頁小程式碼。無path $qcode ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_tokens. ""; $param = json_encode(array("scene"=>$scene_str)); $result = $this->httpRequest( $qcode, $param,"POST"); $filename = './Images/'.'xcx_'.$mpid.'-'.uniqid() . '.jpg'; //定義圖片名字及格式 file_put_contents($filename,$result); return $filename; } //把請求傳送到微信伺服器換取二維碼 function httpRequest($url, $data='', $method='GET'){ $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl, CURLOPT_AUTOREFERER, 1); if($method=='POST') { curl_setopt($curl, CURLOPT_POST, 1); if ($data != '') { curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } } curl_setopt($curl, CURLOPT_TIMEOUT, 30); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($curl); curl_close($curl); return $result; } }
小程式端場景id接收,走介面繫結
注意引數獲取方式 業務場景較多的小程式碼,使用getwxacodeunlimit獲取,其引數需要注意,可不是?id=2, 掃碼訪問內容頁面,在頁面的onload方法中,解析小程式碼的引數 比如要傳入一個使用者id=12,scene引數就可以寫成"12",多個引數按一定規則分開,如&符號,第二個引數是shop_id=3, 則scene可以這樣寫"12&3" 使用者掃碼進入後的邏輯 我們可以在該頁面的onload生命週期中處理引數 onLoad:function(options){ if(options.scene){ let scene=decodeURIComponent(options.scene); //&是我們定義的引數連結方式 let id=scene.split("&")[0]; let shop_id=scene.split('&')[1]; //其他邏輯處理。。。。。 } }