微信公众号消息通知(原生)

需求

1.商品有购买 则通知管理员(可选择)
2.通过PHPQRcode生成扫码绑定管理员
3.扫完码获取信息顺便传个是否应用的参数

流程

1.通过PHPQRcode生成关注公众号二维码

/*分永久和限时详细看文档
* https://developers.weixin.qq.com/doc/offiaccount/Account_Management/Generating_a_Parametric_QR_Code.html
*/

<?php
set_time_limit(30);

class WxQrcode{
    //构造方法
    static $qrcode_url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?";
    static $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&";
    static $qrcode_get_url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?";

    //生成二维码
    public function getEwm($fqid,$type = 1){
        $appid = 'appid';
        $secret = 'secret';
        $ACCESS_TOKEN = $this->getToken($appid,$secret);
        $url = $this->getQrcodeurl($ACCESS_TOKEN,$fqid,$type);
        return $this->DownLoadQr($url,time());
    }

    protected function getQrcodeurl($ACCESS_TOKEN,$fqid,$type = 1){
        $url = self::$qrcode_url.'access_token='.$ACCESS_TOKEN;
        if($type == 1){
            //生成永久二维码
            $qrcode= '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_str": '.$fqid.'}}}';
        }else{
            //生成临时二维码
            $qrcode = '{"expire_seconds": 604800, "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": '.$fqid.'}}}';
        }
        $result = $this->http_post_data($url,$qrcode);
        $oo = json_decode($result[1]);
        if (empty($oo->ticket)){
            return false;
        }
        if(!$oo->ticket){
            $this->ErrorLogger('getQrcodeurl falied. Error Info: getQrcodeurl get failed');
            exit();
        }
        $url = self::$qrcode_get_url.'ticket='.$oo->ticket.'';
        return $url;
    }

    protected function getToken($appid,$secret){
        $ACCESS_TOKEN = file_get_contents(self::$token_url."appid=$appid&secret=$secret");
        $ACCESS_TOKEN = json_decode($ACCESS_TOKEN);
        $ACCESS_TOKEN = $ACCESS_TOKEN->access_token;
        return $ACCESS_TOKEN;
    }

    protected function http_post_data($url, $data_string) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        curl_exec($ch);
        if (curl_errno($ch)) {
            $this->ErrorLogger('curl falied. Error Info: '.curl_error($ch));
        }
        $return_content = ob_get_contents();
        ob_end_clean();
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return array($return_code, $return_content);
    }

    //下载二维码到服务器
    protected function DownLoadQr($url,$filestring){
        if($url == ""){
            return false;
        }
        $filename = $filestring.rand(0,99999999999).'.jpg';
        ob_start();
        readfile($url);
        $img=ob_get_contents();
        ob_end_clean();
        $size=strlen($img);
        $fp2=fopen('./code_img/'.$filename,"a");
        if(fwrite($fp2,$img) === false){
            $this->ErrorLogger('dolwload image falied. Error Info: 无法写入图片');
            exit();
        }
        fclose($fp2);
        return './'.$filename;
    }

    //错误日志
    private function ErrorLogger($errMsg){
        $logger = fopen('log.txt', 'a+');
        fwrite($logger, date('Y-m-d H:i:s')." Error Info : ".$errMsg."\r\n");
        fclose($logger);
    }
}
$qrcode = new WxQrcode();
$qrcode->getEwm(5);

2.扫码获取用户信息写入数据库

<?php 
//引用QRCODE类
require_once('./phpqrcode/phpqrcode.php');
//引用数据库配置
require_once("../../include/config.php");


 class Wx_Gzh{
	  private $appid = "appid";
	  private $appsecret = "appsecret";
	  
	  /**
	   * 获取access_token码
	   */
	  public function getToken(){
		   $appid = $this->appid;
		   $appsecret = $this->appsecret;
		   $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
		   $Token = file_get_contents($url);
		   $Token = json_decode($Token);
		   $Token = $Token->access_token;
		   return $Token;
	  }
	  
	  
	  
	  /**
	   * 获取模板
	   */
	  public function getTemple($content){
	   $access_token = $this->getToken();
	   $data = array();
	   $data['url'] = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
	   $data['content'] = json_encode($content);
	   $data['content'] = urldecode($content);
	   $ch = curl_init();
	   curl_setopt($ch,CURLOPT_URL,$data);
	   curl_setopt($ch,CURLOPT_HEADER,false);
	   curl_exec($ch);
	   curl_close($ch);
	  }
	  
	  public function getJson($url){
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		$output = curl_exec($ch);
		curl_close($ch);
		return json_decode($output,true);
	  }
	  
	  /**
	   * 扫码获取信息
	   */
	   
	   public function getUserinfo(){
	    	$appid = $this->appid;
	    	$appsecret = $this->appsecret;
	    	$data = array();
	    	
	    	//$code是回调的时候地址上带的,只需要get方式接收就可以了
	    	$code = $_GET["code"];
	    	
	    	//获取传过去的值
	    	$cid = $_GET["id"];
	    	
	    	//第一步:取得openid
	    	$oauth2Url ="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
	    	$oauth2 = $this->getJson($oauth2Url);
	    	
	    	//第二步:根据全局access_token和open_id查询用户信息
	    	$access_token = $oauth2["access_token"];
	    	$openid = $oauth2["openid"];
	    	$get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
	    	$userInfo = $this->getJson($get_user_info_url);
	    	$data['openid'] = $userInfo['openid'];//微信用户openid
	    	$data['sex'] = $userInfo['sex'];//性别
	    	$data['headimgurl'] = $userInfo['headimgurl'];//头像
	    	$data['province'] = $userInfo['province'];//地区省
	    	$data['city'] = $userInfo['city'];//地区市
	    	$data['time'] = time();//创建时间
	    	$data['scene'] = $cid;//传过来的值
	    	$data['nickname'] = $userInfo['nickname']; //昵称
	    	mysql_select_db($dbname);
	    	$select = "SELECT * FROM weixin_admin WHERE openid='".$data['openid']."'";
	    	$rt = mysql_query($select);
	    	$column = mysql_fetch_row($rt);
	    	if($column){
	    		echo '<script>alert("用户已绑定!");</script>';
	    	}else{
		    	$insert = "INSERT INTO weixin_admin(openid,sex,headimgurl,province,city,time,scene,nickname)
		    	VALUES( '".$data['openid']."',".$data['sex'].",'".$data['headimgurl']."','".$data['province']."','".$data['city']."',".$data['time'].",".$data['scene'].",'".$data['nickname']."')";
		    	if(mysql_query($insert)){
		    		echo "<script>alert('绑定成功请刷新页面!');</script>";
		    	}else{
		    		echo "非法操作!";
		    	}
	    	}
	   }
 }
 $test = new Wx_Gzh();
 $test->getUserinfo();

3.拿到openid等参数发送绑定参数

class wx_Send{
	private $appid = "appid";
	private $appsecret = "appsecret";
	public function getToken(){
	   $appid = $this->appid;
	   $appsecret = $this->appsecret;
	   $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
	   $Token = file_get_contents($url);
	   $Token = json_decode($Token);
	   $Token = $Token->access_token;
	   return $Token;
    }
    
    public function send_Message($arr_fields){
	   		$access_token = $this->getToken();
	   		$data = array();
	   		$data['url'] = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$access_token";
	   		$data['fields'] = json_encode($arr_fields);
	   		$data['fields'] = urldecode($data['fields']);
	   		
	   		$ch = curl_init();
	   		curl_setopt($ch,CURLOPT_URL,$data['url']);
	   		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	   		curl_setopt($ch,CURLOPT_POST,1);
	   		curl_setopt($ch,CURLOPT_POSTFIELDS,$data['fields']);
	   		$json_result = curl_exec($ch);
	   		curl_close($ch);
	   		return json_decode($json_result,true);
	}
	
	 public function send_Payment($str_openid,$str_first,$str_keyword1,$str_keyword2,$str_keyword3,$str_keyword4,$str_remark,$str_color="#173177"){
			$arr_msg_data = array();
			$arr_msg_data['first'] = array('value'=>$str_first,'color'=>$str_color);
			$arr_msg_data['keyword1'] = array('value'=>$str_keyword1,'color'=>$str_color);
			$arr_msg_data['keyword2'] = array('value'=>$str_keyword2,'color'=>$str_color);
			$arr_msg_data['keyword3'] = array('value'=>$str_keyword3,'color'=>$str_color);
			$arr_msg_data['keyword4'] = array('value'=>$str_keyword4,'color'=>$str_color);
			$arr_msg_data['remark'] = array('value'=>$str_remark,'color'=>$str_color);
			$data = array();
			$data["touser"] = $str_openid;
			//模板id
			$data["template_id"] = "templateid";
			$data["topcolor"] = $str_color;
			$data["data"] = $arr_msg_data;
			$arr_result = $this->send_Message($data);
			return $arr_result;
	 }
}

	/**
	* 微信发送模板消息
	 * $str_openid:微信用户ID
	 * $str_first:消息模板简介
	 * $str_keyword*:内容详细看模板
	 * $str_remark:备注
	 * $str_color:颜色 
	 */
		$str_first = $leixing;
		$str_keyword1 = $price;
		$str_keyword2 = $medianame;
		$str_keyword3 = $order_id;
		$str_keyword4 = $VipUser;
		$str_remark = $data;
				
				
		$select_opid = "SELECT openid FROM weixin_admin where scene=1";
		$opid = mysql_query($select_opid);
		$oid = mysql_fetch_row($opid);
		$send = new wx_Send();
		$send->send_Payment($oid[0],$str_first,$str_keyword1,$str_keyword2,$str_keyword3,$str_keyword4,$str_remark);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值