微信公衆号裂變式營銷代碼實作,先講下基礎原理,先生成帶有使用者參數的二維碼,然後用php自帶的gd庫處理,生成帶有使用者頭像,昵稱,參數二維碼,營銷資訊的自定義圖檔,再将圖檔傳入微信公衆号臨時素材,當其他使用者掃描這個專屬推薦碼的時候,擷取使用者的昵稱傳回給推薦者,并存入資料庫,以記錄目前有多少人掃描了二維碼。
技術難點:
1.gd庫處理圖檔,以前沒玩過gd庫,gd庫很難用,建議如果不懂gd庫,可以直接嘗試其他的php圖像處理擴充。
2.生成使用者參數二維碼,參數二維碼選擇臨時二維碼,參數選擇字元串參數,字元串是推薦者的openid,因為openid是唯一的,是使用者的辨別,當然你也可以自己為使用者設定辨別,而且效率更高。
3.判斷關注事件,是否是通過參數二維碼進來的,判斷方法可查微信公衆号開發文檔的關注事件推送。
4.應用到的技術:PHP,curl擴充,gd擴充,mysqli,
話不多說,直接上代碼,還有其他想了解的,直接留言。
第一段代碼,yanzheng.php,用來接收微信端傳回的資訊的,如果自己有,請不要照抄,直接看關注事件部分以及自定義菜單,有注釋。
<?php
/**
* wechat php test
*/
//define your token
// session_start();
//定義TOKEN秘鑰
define("TOKEN", "weixin");
//執行個體化微信對象
$wechatObj = new wechatCallbackapiTest();
//驗證成功後注釋valid方法
// $wechatObj->valid();
//開啟自動回複功能
$wechatObj->responseMsg();
//定義類檔案
class wechatCallbackapiTest
{
//實作valid驗證方法:實作對接微信公衆平台
public function valid()
{
//接受随機字元串
$echoStr = $_GET["echostr"];
//valid signature , option
//進行使用者數字簽名驗證
if($this->checkSignature()){
//如果成功,則傳回接受到的随機字元串
echo $echoStr;
//退出
exit;
}
}
//定義自動回複功能
public function responseMsg()
{
//get post data, May be due to the different environments
//接受使用者端發送過來的xml資料
$postStr = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
//extract post data
//判斷xml資料是否為空
if (!empty($postStr)){
/* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
the best way is to check the validity of xml by yourself */
libxml_disable_entity_loader(true);
//通過simplexml進行xml解析
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
//接受微信的手機端
$fromUsername = $postObj->FromUserName;
//微信公衆平台
$toUsername = $postObj->ToUserName;
//接受使用者發送的關鍵詞
$keyword = trim($postObj->Content);
//1.接受使用者消息類型
$msgType = $postObj -> MsgType;
//時間戳
$time = time();
//事件類型
$event = $postObj->Event;
//自定義菜單事件K值
$eventkey = $postObj->EventKey;
$ticket=$postObj->Ticket;
//文本發送模闆
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";
//圖檔發送模闆
$imageTpl = "<xml>
<ToUserName>< ![CDATA[%s] ]></ToUserName>
<FromUserName>< ![CDATA[%s] ]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType>< ![CDATA[%s] ]></MsgType>
<Image>
<MediaId>< ![CDATA[%s] ]></MediaId>
</Image>
</xml>
";
//關注事件
if($event=='subscribe') {
$msgType = "text";
$contentStr = "感謝關注德盛康大藥房!
您可以\n
<a href='https://m.xxxx.com/ceshi.php'>線上購藥</a>\n
<a href='https://m.xxxx.com/zixunyaoshi'>藥品咨詢</a>\n
<a href='https://m.xxxx.com/weixin/lxfs.html'>聯系門店</a>";
$resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,$msgType,$contentStr);
echo $resultStr;
if(isset($eventkey)){
$canshu = substr($eventkey,8);
$data = array('canshu' =>$canshu,'openid'=>$fromUsername );
hurl("https://m.xxxxx.com/weixin/moban2.php",$data);
}
}
//掃描帶參數的二維碼的圖檔
// if($event=='subscribe' && isset($eventkey)){
// // $data = $eventkey;
// // hurl("https://m.39dsk.com/weixin/moban2.php",$data);
// // exit("success");
// $msgType = "text";
// $contentStr = substr($eventkey,8);
// $resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,$msgType,$contentStr);
// echo $resultStr;
// }
//自定義菜單事件
if ($event=='CLICK' && $msgType=='event') {
if ($eventkey == "jfhg") {
$contentStr = "您點選了積分換購,很抱歉,該功能未上線!";
$msgType = "text";
$resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,$msgType,$contentStr);
echo $resultStr;
}
if ($eventkey == "mfly") {
$data = $fromUsername;
$contentStr = "已生成您的專屬推薦碼,邀請10位好友掃描關注我們,可免費領取XXX,邀請碼稍有延遲,如不能生成請再次點選免費領藥";
$msgType = "text";
$resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,$msgType,$contentStr);
echo $resultStr;
hurl("https://m.xxxxx.com/weixin/weweima.php",$data);
}
}
//使用者消息事件
if($msgType=='text'&&$keyword=="1"){
$msgType = "text";
$contentStr = "00";
$resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,$msgType,$contentStr);
echo $resultStr;
}
if ($msgType=='text'&&$keyword=="本期活動") {
// $msgType = "text";
// $contentStr = "22";
// $resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,$msgType,$contentStr);
// echo $resultStr;
include_once "kefujiekou2.php";
}
exit("success");
}
}
private function checkSignature()
{
// you must define TOKEN by yourself
//判斷是否定義了TOKEN,如果沒有就抛出一個異常
if (!defined("TOKEN")) {
throw new Exception('TOKEN is not defined!');
}
$signature = $_GET["signature"];//接受微信加密簽名
$timestamp = $_GET["timestamp"];//接受時間戳
$nonce = $_GET["nonce"];//接受随機數
$token = TOKEN;//把TOKEN常量指派給$token
//把相關參數組裝成數組
$tmpArr = array($token, $timestamp, $nonce);
// use SORT_STRING rule
//排序
sort($tmpArr, SORT_STRING);
//把排序後的數組轉換成字元串
$tmpStr = implode( $tmpArr );
//通過雜湊演算法加密
$tmpStr = sha1( $tmpStr );
//與加密簽名進行對比
if( $tmpStr == $signature ){
//相同傳回true
return true;
}else{
//不同傳回false
return false;
}
}
}
function hurl($a,$data){
$th = curl_init();//初始化curl執行個體
curl_setopt($th,CURLOPT_URL,$a);
curl_setopt($th, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($th, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($th, CURLOPT_TIMEOUT, 1);
curl_setopt($th, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($th, CURLOPT_POST, 1);
curl_setopt($th, CURLOPT_POSTFIELDS, $data);
$zz = curl_exec($th);//執行curl
curl_close($th);//關閉curl
return $zz;
}
?>
第二段代碼,erweima .php,主要是對圖檔進行處理,擷取各種參數,隻不過有圖檔儲存到本地和上傳到微信伺服器,是以消耗時間過長,大家有什麼好方法避免,歡迎交流。
<?php
header("Content-type:text/html;charset=utf-8");
$post = file_get_contents('php://input');//設定post消息可讀
$fromUsername = $_POST[0];//接收yanzheng.php傳來的資訊,參加活動的使用者ID
// print_r($_POST[0]);
include_once "access_token.php";//擷取微信公衆号的access_token,微信公衆号為驗證伺服器的身份,access_token是必須的
$url0 = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$fromUsername."&;
$result0 = https_request($url0);
$a0 = json_decode($result0,true);//通過openid擷取使用者的頭像和昵稱
// echo $a0['nickname'] , $a0['headimgurl'];
$jsonmenu = '{"expire_seconds": 2592000, "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str" : "'.$fromUsername.'"}}}';
$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;
$result = https_request($url, $jsonmenu);//生成使用者參數二維碼的ticket,參數二維碼需要用ticket換取,微信公衆号規定,為什麼這麼規定,反正我是想不明白
$a = json_decode($result,true);
$b = UrlEncode($a['ticket']) ;//擷取ticket
$url2 = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$b;
$result2 = https_request($url2); //參數二維碼
// var_dump($result2);
//以下是GD庫處理圖檔部分,不解釋了,看GD庫的文檔吧
$bg = imagecreatefrompng("images/ceshi.png");
$img_info = getimagesize('images/ceshi.png');
$img_w = $img_info[0];
$img_h = $img_info[1];
$im = imagecreatetruecolor($img_w, $img_h);
$black = imagecolorallocate($im, 0, 0, 0);
$red = imagecolorallocate($im, 255, 0, 0);
imagecopy($im,$bg,0,0,0,0,$img_w,$img_h);
$font = "font/msyh.ttf";
$text = $a0['nickname'];
$text2 = '免費送藥,免費咨詢,快來和我一起體驗吧';
imagettftext($im, 14, 0, 300, 970, $black, $font,$text);
imagettftext($im, 18, 0, 140, 1020, $red, $font,$text2);
$img2 = imagecreatefromstring($result2);//帶有參數的二維碼
imagecopyresized($im, $img2, 200, 470, 0, 0,320,320,430, 430);
$img3 = imagecreatefromjpeg($a0['headimgurl']);//使用者頭像圖檔
imagecopyresized($im, $img3, 300, 830, 0, 0,110,103,110, 103);
$img4 = imagecreatefrompng('images/touxiang.png');//二維碼中心的頭像,二維碼被遮蓋一小部分不影響識别,可以參考二維碼原理
imagecopyresized($im, $img4, 320, 600, 0, 0,80,80,500, 500);
$img5 = imagecreatefrompng('images/yx.png');//圓角圖檔
imagecopyresized($im, $img5, 300, 830, 0, 0,110,110,110, 110);
header('Content-Type: image/png');
imagepng($im,'images/'.$fromUsername.'.png');
imagedestroy($im);
//GD庫圖檔處理到此結束,将圖檔儲存到了'images/'.$fromUsername.'.png'!
//以下是
$file = __DIR__."\images\\".$fromUsername.".png";//取出圖檔
// echo $file;
$obj = new CurlFile($file); //CurlFile,php高于5.5,上傳檔案必須要用CurlFile
$post['media'] = $obj;
$url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$access_token."&type=image";
$result = https_request($url,$post); //将圖檔資訊上傳至臨時素材,擷取素材ID
$zz = json_decode($result,true);
$data = '{
"touser":"'.$fromUsername.'",
"msgtype":"image",
"image":
{
"media_id":"'.$zz['media_id'].'"
}
}';
$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
$result = https_request($url,$data); //利用客服接口,發送圖檔資訊到使用者
// var_dump($result);
function https_request($url,$data = null){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
?>
第三段代碼,使用者掃描了帶參數的二維碼,将事件通過模闆消息的方式推送給推薦者,讓他知道是誰掃描了該二維碼
<?php
header("Content-type:text/html;charset=utf-8");
$post = file_get_contents('php://input');
$eventkey = $_POST['canshu'];//擷取關注事件推送來的資訊
$fromUsername = $_POST['openid'];
// $eventkey = "ou1RJxE7SYBEw4DBOBs8EBL0egZ0";
// $fromUsername = "ou1RJxJ0Y7yzT5H9_DG1jp0ybIy0";
if ($eventkey!=$fromUsername) {//判斷不能自己掃自己,如果不加,那麼使用者将圖檔儲存到本地,然後取消關注,掃自己的二維碼關注是可行的。
include_once "access_token.php";//微信驗證
$url0 = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$fromUsername."&;
$result0 = https_request($url0);
$a0 = json_decode($result0,true);
$name = $a0['nickname'];//擷取掃描者的昵稱
include_once "coom.php";//連接配接資料庫,将事件存入資料庫,以便判斷有多少人掃描了二維碼
mysqli_query($conn , "set names utf8");
$sql = "INSERT INTO biaoming ".
"(yqz,byqz) ".
"VALUES ".
"('$eventkey','$fromUsername')";
$sql2 = "SELECT *
FROM biaoming
where yqz = '$eventkey'";
$sql3 = "UPDATE biaoming
SET wancheng=1
WHERE yqz ='$eventkey'";
//biaoming = “表名”,yqz="推薦者的ID" ,byqz = "掃描者的ID"
mysqli_select_db( $conn, 'liuyanfankui');
$retval = mysqli_query( $conn, $sql );
$retval2 = mysqli_query( $conn, $sql2 );
$num = mysqli_num_rows($retval2);
$hsx = 10-$num;
if ($hsx<=0 ) {
$tt = "任務完成,請進入微信商城-->個人中心-->修改位址,填寫收件資訊,我們會盡快為您配送,如已填寫,請忽略";
$retval3 = mysqli_query( $conn, $sql3 );
}else{
$tt = "邀請10位好友加入我們,就能獲得德盛康大藥房免費贈送的XXX,已邀請".$num."位,還差".$hsx."位";
}
if (!$retval) {
echo "插入失敗";
}
mysqli_close($conn);
//以下發送模闆消息,請檢視微信公衆号開發文檔
$time = date("Y-m-d H:i:s");
$jsonmenu = ' {
"touser":"'.$eventkey.'",
"template_id":"模闆素材ID",
"data":{
"first": {
"value":"'.$name.'通過您的二維碼成為了我們的朋友!",
"color":"#173177"
},
"keyword1":{
"value":"免費領藥",
"color":"#173177"
},
"keyword2": {
"value":"'.$time.'",
"color":"#173177"
},
"remark":{
"value":"'.$tt.'",
"color":"#ff0000"
}
}
}';
$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
$result = https_request($url,$jsonmenu);
var_dump($result);
//以上為發送模闆消息
}
function https_request($url,$data = null){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
?>
到此,功能基本開發完畢,但也有一些不完美的地方,最主要的是儲存參數二維碼到本地,然後上傳參數二維碼到微信伺服器,這段代碼耗時太長,歡迎學習交流。
有問題的,歡迎留言,本人原創