微信小程序分享二维码生成

生成微信小程序分享二维码

微信小程序官方开放的二维码的接口,其中有一个是生成小程序二维码的,还有一个是圆形的小程序码,我这里就用php生成二维码。

完整代码:

  public function share($product_id, $user_id) {
       //首先要获取Access_token 。注意:access_token只有2小时有效期,所以要缓存最好,避免重复请求
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . config('appid') . "&secret=" . config('secret');
        $json = $this->httpRequest($access_token);
        $json = json_decode($json, true);
        //width是二维码宽度
        $qcode = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" . $json['access_token'];
        $param = json_encode(array("path" => "/pages/public/product/product?id=" . $product_id . "&parent_id=" . $user_id . "&product_id=" . $product_id, "width" => 150));  //path 是小程序的落地页(小程序分享页面)后面可以带参数 
        //POST参数
        $result = $this->httpRequest($qcode, $param, "POST");
        //生成二维码
        $file_name = '/home/resource/' . time() . rand(1000, 9999) . '.jpg';
        file_put_contents($file_name, $result);
        // $base64_image = base64_encode('data:image/png;base64'.$result);
        $qiniuConfig = config('qiniu');
        $auth = new Auth($qiniuConfig['accessKey'], $qiniuConfig['secretKey']);
        $key = time() . rand(1000, 9999) . '.jpg';
        $upToken = $auth->uploadToken($qiniuConfig['merchantBucket'], $key, 3600); //获取上传所需的toke
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($upToken, $key, $file_name);
        if (empty($err)) {
            unlink($file_name); //删除本地图片
        } else {
            return DataReturnService::returnError(-1, '获取分享商品二维码失败', ['']);
        }
        $ret['key'] = $qiniuConfig['merchantDomain'] . $ret['key'];

        return DataReturnService::returnOk($ret, '获取分享商品二维码成功');

    }
public function httpRequest($url, $data = '', $method = 'GET') {
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
		if ($method == 'POST') {
			curl_setopt($curl, CURLOPT_POST, 1);
			if ($data != '') {
				curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
			}
		}

		curl_setopt($curl, CURLOPT_TIMEOUT, 30);
		curl_setopt($curl, CURLOPT_HEADER, 0);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$result = curl_exec($curl);
		curl_close($curl);
		return $result;
	}

你可能感兴趣的:(小程序开发)