激情综合色五月六月婷婷,久久久久久综合网天天,国产精品久久久久精品综合紧无码

  • 2022-10-27
宇哥博客 前端開發 WordPress關注微信公眾號可見代碼,為公眾號引流

WordPress關注微信公眾號可見代碼,為公眾號引流

WordPress上發布一篇文章,為了讓真實用戶才能看到隱藏部分的內容,這時候可以讓用戶關注微信公眾號,發送指定的驗證碼,驗證成功后顯示隱藏的內容,間接的也為公眾號引流。

開始

首先是要怎樣指定文章中的那部分內容隱藏。

發布文章時,將需要隱藏的內容放在<yg_wx></yg_wx>中間,例如“<yg_wx>這里是要隱藏的內容</yg_wx>”。

add_filter('the_content', 'weixin_secret');
function weixin_secret($content){
    global $post,$wpdb;
	$post_id = $post->ID;
    if (preg_match_all('#<yg_wx>([\s\S]*?)</yg_wx>#i', $content, $secret_content)){
        $user_id = is_user_logged_in() ? wp_get_current_user()->ID : 0;
		$ygwx = new YGWX($post_id, $user_id);
        if( !$ygwx->is_paid() ){
            $secret_notice = '<style type="text/css">.erphp-wx {background-color: #fff;border: 2px dashed #ff5f33;color: #333;font-size: 14px;line-height: inherit;padding: 5px 10px;}</style>
            <div class="erphp-wx">
				您需要關注公眾號并發送驗證碼,驗證成功后才能查看此處內容!<a href="javascript:;" class="erphp-wx-loader" data-post="'.$post_id.'" >立即關注</a>
			</div>
			<script type="text/javascript" src="/static/js/wpwx.js?v=1.0"></script>
			<script type="text/javascript" src="http://www.layuicdn.com/layui/layui.js"></script>
			<link rel="stylesheet"  type="text/css"/>
			';
            $content = str_replace($secret_content[0], $secret_notice, $content);
        }
    }
    return $content;
}

點擊“立即關注”后,生成隨機的6位驗證碼,Ajax傳到前臺。

前端代碼:

    var ygwx_order;
    var ygwx_timer;
    /**
     * 立即關注 
     */
    $(".erphp-wx-loader").on("click",function(){
        var post_id = $(this).data("post");
        
        console.log('立即關注', post_id);
        
        clearInterval(ygwx_order);
        clearInterval(ygwx_timer);

    	var layer = layui.layer;
      
        $.ajax({
            url: '/wp-admin/admin-ajax.php',
            type: 'POST',
        data: {action:'ygwx' ,post_id: post_id },
         dataType: 'json',
         success:function(data){
             //console.log('xx', data);
             let code = data.code;
             let qrcode = data.qrcode;
             
             var alert1 = layer.open({
            	    title: '',
            		// shade: 0.8
            		shade: ["0.4","#ddd"],
            		// shade: false
            		btn: [], //默認有‘確定’按鈕,去掉
            		content: '<div class="yg-open"><div><img class="weixin-qrcode" src="'+qrcode+'" /></div><div>掃碼關注公眾號,發送驗證碼【'+code+'】至該公眾號。</div><div class="ygtime"></div></div>',
            		end: function(){
            		    //點擊關閉后回調
                        //layer.msg('close');//layer.closeAll();
                        clearInterval(ygwx_order);
                        clearInterval(ygwx_timer);
                    }
            	});
                var m = data.minute;
                ygwx_order = setInterval(function() {
                    $.post('/wp-admin/admin-ajax.php', {
                        "action": "ygwx_wx",
                        "post_id": post_id,
                        "order_num": data.num
                    }, function(data) {
                        if(data.status == "1"){
                            clearInterval(ygwx_order);
                            layer.msg("驗證成功",{
                        		icon: 6,
                        		time: 1000
                        	},function(){
                        	    location.reload();    
                        	});
                            
                        }
                    });
                }, 5000);
                
                var s = 0;  
                ygwxCountdown();
                ygwx_timer = setInterval(function(){ ygwxCountdown(); },1000);
                function ygwxCountdown(){
                    $(".ygtime").html("驗證倒計時:<span>0"+m+"分"+s+"秒</span>");
                    if( m == 0 && s == 0 ){
                        clearInterval(ygwx_order);
                        clearInterval(ygwx_timer);
                        //console.log('監聽結束.....2');
                        layer.msg('驗證碼超時,請重新獲取');
                        layer.closeAll();
                        m = 4;
                        s = 59;
                    }else if( m >= 0 ){
                        if( s > 0 ){
                            s--;
                        }else if( s == 0 ){
                            m--;
                            s = 59;
                        }
                    }
                }
             
           },
         error:function(e){
            console.log('ee', e);
            layer.msg('調取微信公眾號失敗');
          }

      });
    }); 

后臺鉤子代碼:

/***********************************************************************/
function ygwx_callback(){
	$post_id = $_POST['post_id'];
	$user_id = is_user_logged_in() ? wp_get_current_user()->ID : 0;
	$code='';
	$msg='';$num='';$status=400;$minute=0;
	$qrcode='';
	$out_trade_no = date("ymdhis").mt_rand(100,999).mt_rand(100,999).mt_rand(100,999);
    $minute = 3;
	if(1==1){
		$ygwx = new YGWX($post_id, $user_id);
		$code = '123456';//隨機6位數字,這里就先固定了
		if($ygwx->add($out_trade_no, $code)){
			$num = $out_trade_no;
			$status=200;
		}
	}
	$result = array(
		'status' => $status,
		'code' => $code,
		'qrcode'=> '微信二維碼地址',
		'num' => $num,
		'minute' => $minute,
		'msg' => $msg
	);
	header('Content-type: application/json');
	echo json_encode($result);
	exit;
}
add_action( 'wp_ajax_ygwx', 'ygwx_callback');
add_action( 'wp_ajax_nopriv_ygwx', 'ygwx_callback');
/***********************************************************************/



/****************************定時查詢是否已經驗證成功*******************************************/
function ygwx_wx_callback(){
	$post_id = $_POST['post_id'];
	$order_num = $_POST['order_num'];
	$status = 0;
	$user_id = is_user_logged_in() ? wp_get_current_user()->ID : 0;
	$ygwx = new YGWX($post_id, $user_id);
	if($ygwx->check_send($order_num)){
		$days = 1;
		$expire = time() + $days*24*60*60;
	    setcookie('ygwx_'.$post_id, $wppay->set_key($order_num), $expire, '/', $_SERVER['HTTP_HOST'], false);
	    $status = 1;
	}
	$result = array(
		'status' => $status
	);
	header('Content-type: application/json');
	echo json_encode($result);
	exit;
}
add_action( 'wp_ajax_ygwx_wx', 'ygwx_wx_callback');
add_action( 'wp_ajax_nopriv_ygwx_wx', 'ygwx_wx_callback');
/****************************定時查詢是否已經驗證成功*******************************************/

classYGWX代碼:

<?php

class YGWX{
    
    private		$ip;
	public		$post_id;
	public		$user_id;
	
	public function __construct($post_id, $user_id){
		$this->ip = $_SERVER['REMOTE_ADDR'];
		$this->post_id = $post_id;
		$this->user_id = $user_id?$user_id:0;
	}
	
	public function check_send($order_num){
		global $wpdb, $ygwx_table_name;
		$wppay_check = $wpdb->get_var($wpdb->prepare("SELECT id FROM $ygwx_table_name
										WHERE	post_id = %d
										AND     order_status = 1
										AND		order_num = %s", $this->post_id, $order_num));
		$wppay_check = intval($wppay_check);
		return $wppay_check && $wppay_check > 0;
	}
    
	public function add($order_num,$code){
		date_default_timezone_set('Asia/Shanghai');
		global $wpdb, $ygwx_table_name;
		$result = $wpdb->insert($ygwx_table_name, array(
			'order_num' => $order_num,
			'post_id' => $this->post_id,
			'user_id' => $this->user_id,
			'create_time' => date("Y-m-d H:i:s"),
			'order_code' =>$code,
			'ip_address' => $this->ip), array('%s', '%d', '%s', '%s', '%s', '%s'));
		if($result){
	    	return true;
	    }
	    return false;
	}    
	
	public function is_paid(){
		global $wpdb, $ygwx_table_name;
		if( isset($_COOKIE['ygwx_'.$this->post_id]) ){
			$order_num = $this->get_key($_COOKIE['ygwx_'.$this->post_id]);
			$wppay_check = $wpdb->get_var($wpdb->prepare("SELECT id FROM $ygwx_table_name
										WHERE	post_id = %d
										AND     order_status = 1
										AND		order_num = %s", $this->post_id, $order_num));
			$wppay_check = intval($wppay_check);
			return $wppay_check && $wppay_check > 0;
		}
		return 0;
	}
	
	public function get_key($key){
		return str_replace( md5('1234'), '', base64_decode($key) );
	}
	
	public function set_key($order_num){
		return base64_encode($order_num.md5('1234'));
	}
}

下面是接管微信公眾號,接收用戶發送過來的驗證碼。

將下面的代碼保存至網站根目錄,例如:wx.php

微信公眾號后臺開發者模式,URL填寫“http://www.xxx.com/wx.php”,token填寫“token”。


define("WEIXIN_TOKEN", "token");

$wechatObj = new WxApi();
$wechatObj->valid();

class WxApi
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = file_get_contents('php://input');
        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_use_internal_errors(true);//關閉xml錯誤 
                libxml_disable_entity_loader(true);
                $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $msgType = $postObj->MsgType;
                $keyword = trim($postObj->Content);
                $time = time();

                if(!empty( $keyword ) && $msgType == 'text' && preg_match("/^[0-9]{6}$/", $keyword)){
                    //6位數字
                    $textTpl = "<xml>
  <ToUserName><![CDATA[%s]]></ToUserName>
  <FromUserName><![CDATA[%s]]></FromUserName>
  <CreateTime>%s</CreateTime>
  <MsgType><![CDATA[%s]]></MsgType>
  <Content><![CDATA[%s]]></Content>
</xml>";
                    $msgType = "text";
                    $contentStr = '';
                    
                    //這種方式有問題,像是服務環境的問題
                    /*
                    define('WP_USE_THEMES', false);
                    require('wp-blog-header.php');
 
                    define( 'WP_DEBUG_DISPLAY', true ); 
                    ini_set( 'display_errors', true );

                    global $wpdb;
    
                    $ygwx_table_name = 'wp_ygwx';
                    //5分鐘內創建的
                    $ygwx_id = $wpdb->get_var("SELECT id FROM {$ygwx_table_name} WHERE order_code='{$keyword}' and order_status=0 and TIMESTAMPDIFF(SECOND, create_time,now()) <= 300  limit 1");
                    if($ygwx_id){
                        //驗證成功
                        $r = $wpdb->query("update {$ygwx_table_name} set order_status=1,order_time=NOW(),openid='{$fromUsername}' where id={$ygwx_id}");
                        if($r){
                            $contentStr = '驗證成功,請前往頁面查看內容。';    
                        }
                    }else{
                        $contentStr = '驗證碼驗證失敗。';
                    }
                    */
                    
                    $ygwx_table_name = 'wp_ygwx';
                    //5分鐘內創建的
                    $ygwx_arr = $this->getOneData("SELECT id FROM {$ygwx_table_name} WHERE order_code='{$keyword}' and order_status=0 and TIMESTAMPDIFF(SECOND, create_time,now()) <= 300  limit 1");
                    if($ygwx_arr){
                        //驗證成功
                        $id = $ygwx_arr['id'];
                        $r = $this->updateData("update {$ygwx_table_name} set order_status=1,order_time=NOW(),openid='{$fromUsername}' where id={$id}");
                        if($r){
                            $contentStr = '驗證成功,請前往頁面查看內容。';    
                        }
                    }else{
                        $contentStr = '驗證碼驗證失敗。';
                    }
                  
                    //file_put_contents("test.txt","*2".$postStr .date('Y-m-d H:i:s')."\r\n",FILE_APPEND);

                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
					header("Content-type: application/xml");
                    echo $resultStr;
                    exit;
                }else{
                    echo "success";
                }

        } else {
            echo "";
            exit;
        }
    }
        
    private function checkSignature()
    {

        if (!defined("WEIXIN_TOKEN")) {
            throw new Exception('WEIXIN_TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
                
        $token = WEIXIN_TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
    
    /**
     * 返回一條數據
     */
    public function getOneData($sql){
        require('wp-config.php');
        $mysql_server="localhost";
        $mysql_username = DB_USER;
        $mysql_password= DB_PASSWORD;
        $mysql_database= DB_NAME;
        
        $db=new mysqli($mysql_server,$mysql_username,$mysql_password,$mysql_database);
        if(mysqli_connect_error()){
            echo 'Could not connect to database.';
            exit;
        }
        $result=$db->query($sql);
        $row=$result->fetch_assoc();
        mysqli_close($db);
        return $row;
    }
    
    public function updateData($sql){
        require('wp-config.php');
        $mysql_server="localhost";
        $mysql_username = DB_USER;
        $mysql_password= DB_PASSWORD;
        $mysql_database= DB_NAME;
        
        $db=new mysqli($mysql_server,$mysql_username,$mysql_password,$mysql_database);
        if(mysqli_connect_error()){
            echo 'Could not connect to database.';
            exit;
        }
        $x=mysqli_query($db, $sql);
        mysqli_close($db);
        return $x;
    }
}

以上代碼大概就實現了需要的功能。

更多

測試體驗地址:http://www.callingbugs.com/1580.html

本文來自網絡,不代表本站立場,轉載請注明出處。http://www.callingbugs.com/3064.html

發表評論

您的電子郵箱地址不會被公開。

返回頂部
激情综合色五月六月婷婷,久久久久久综合网天天,国产精品久久久久精品综合紧无码