51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

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="//www.layuicdn.com/layui/layui.js"></script>
			<link rel="stylesheet" href="//www.layuicdn.com/layui/css/layui.css" 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("验证倒计时:&lt;span&gt;0"+m+"分"+s+"秒&lt;/span&gt;");
                    if( m == 0 &amp;&amp; s == 0 ){
                        clearInterval(ygwx_order);
                        clearInterval(ygwx_timer);
                        //console.log('监听结束.....2');
                        layer.msg('验证码超时,请重新获取');
                        layer.closeAll();
                        m = 4;
                        s = 59;
                    }else if( m &gt;= 0 ){
                        if( s &gt; 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-&gt;ip = $_SERVER['REMOTE_ADDR'];
    	$this-&gt;post_id = $post_id;
    	$this-&gt;user_id = $user_id?$user_id:0;
    }

    public function check_send($order_num){
    	global $wpdb, $ygwx_table_name;
    	$wppay_check = $wpdb-&gt;get_var($wpdb-&gt;prepare("SELECT id FROM $ygwx_table_name
    									WHERE	post_id = %d
    									AND     order_status = 1
    									AND		order_num = %s", $this-&gt;post_id, $order_num));
    	$wppay_check = intval($wppay_check);
    	return $wppay_check &amp;&amp; $wppay_check &gt; 0;
    }

    public function add($order_num,$code){
    	date_default_timezone_set('Asia/Shanghai');
    	global $wpdb, $ygwx_table_name;
    	$result = $wpdb-&gt;insert($ygwx_table_name, array(
    		'order_num' =&gt; $order_num,
    		'post_id' =&gt; $this-&gt;post_id,
    		'user_id' =&gt; $this-&gt;user_id,
    		'create_time' =&gt; date("Y-m-d H:i:s"),
    		'order_code' =&gt;$code,
    		'ip_address' =&gt; $this-&gt;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-&gt;post_id]) ){
    		$order_num = $this-&gt;get_key($_COOKIE['ygwx_'.$this-&gt;post_id]);
    		$wppay_check = $wpdb-&gt;get_var($wpdb-&gt;prepare("SELECT id FROM $ygwx_table_name
    									WHERE	post_id = %d
    									AND     order_status = 1
    									AND		order_num = %s", $this-&gt;post_id, $order_num));
    		$wppay_check = intval($wppay_check);
    		return $wppay_check &amp;&amp; $wppay_check &gt; 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-&gt;FromUserName;
                $toUsername = $postObj-&gt;ToUserName;
                $msgType = $postObj-&gt;MsgType;
                $keyword = trim($postObj-&gt;Content);
                $time = time();

                if(!empty( $keyword ) &amp;&amp; $msgType == 'text' &amp;&amp; preg_match("/^[0-9]{6}$/", $keyword)){
                    //6位数字
                    $textTpl = "&lt;xml&gt;




\<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-&gt;get_var("SELECT id FROM {$ygwx_table_name} WHERE order_code='{$keyword}' and order_status=0 and TIMESTAMPDIFF(SECOND, create_time,now()) &lt;= 300  limit 1");
                    if($ygwx_id){
                        //验证成功
                        $r = $wpdb-&gt;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-&gt;getOneData("SELECT id FROM {$ygwx_table_name} WHERE order_code='{$keyword}' and order_status=0 and TIMESTAMPDIFF(SECOND, create_time,now()) &lt;= 300  limit 1");
                    if($ygwx_arr){
                        //验证成功
                        $id = $ygwx_arr['id'];
                        $r = $this-&gt;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-&gt;query($sql);
        $row=$result-&gt;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.ygbks.com/1580.html

赞(5)
未经允许不得转载:工具盒子 » WordPress关注微信公众号可见代码,为公众号引流