<?php
/**
 * Created by PhpStorm.
 * User: liyiming
 * Date: 2019/8/8
 * Time: 14:23
 */
# 生成二维码
class WxTCode{
    protected $appid = '';
    protected $secret = '';protected $access_tokens = "";
    public function __construct($appid,$secret){
        $this->appid = $appid;
        $this->secret = $secret;
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->secret . "";
        $result = $this->curl_post($url);
        $this->access_tokens = $result['access_token'];
    }




    public function ShowCode(){
        $rs = $this->getTemporaryQrcode($this->access_tokens, 123);
        $ticket = $rs['ticket'];
        $qrcode = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . $ticket . "";
        # 当前页直接显示
        Header("Location:$qrcode");
    }


    /**
     *   生成二维码
     * @param $access_tokens
     * @param $orderId
     * @return mixed
     */
    public function getTemporaryQrcode($access_tokens, $orderId){
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $access_tokens . "";
        # 生成二维码需要的参数
        $qrcode = '{"expire_seconds": 1800, "action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": ' . $orderId . '}}}';
        $result = $this->curl_post($url, $qrcode);
        return $result;
    }

    /**
     * @param $url
     * @param null $data
     * @param string $method
     * @param bool $https
     * @return mixed
     */
    private function curl_post($url, $data=null,$method='POST', $https=true){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if($https){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            if($method == 'POST'){
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            }
            $content = curl_exec($ch);
            curl_close($ch);
            return json_decode($content,true);
        }
    }
}

$Wxfollow = new WxTCode('appid','secret');
$follow = $Wxfollow->ShowCode();
03-25 19:35