小程序二维码

白与黑 2021-02-08 21:14:00 1124℃ 11595 0条

微信分享包括获取分享二维码,分享到好友,分享到朋友圈。获取分享二维码只需要后端将生成的二维码地址传递给前端即可;分享到好友是前端程序员的任务,不需要后端操作

生成微信二维码

<?php

use Tools\CurlService;
use Tools\WxAccessToken;

define('APP_ID', '12345');
define('APP_SECRET','56789');

class ShareService
{
    /**
     * @param $code             string 链接参数
     * @param $title            string 主体文字
     * @param $productImg       string 主体图片
     * @return array
     */
    public function wxShareImg($code, $title, $productImg)
    {
        $result = [
            'success' => true,
            'message' => '',
            'url'     => '',
        ];
        if (empty($title) || empty($productImg)) {
            $result['success'] = false;
            $result['message'] = '参数缺失';
            return $result;
        }
        WxAccessToken::init(APP_ID, APP_SECRET);
        $token = WxAccessToken::getAccessToken();
        // 二维码链接
        $path          = 'packageC/pages/goodsDetail/goodsDetail?code=' . $code;
        // 小程序图片
        $buildQcodoRes = $this->createWxaCode($path, $token);
        if (false === $buildQcodoRes['success']) {
            return $buildQcodoRes;
        }
        $path = 'data/upload/productShare/' . date('ymd') . '/qrcode/';
        $file = $path . uniqid() . '.jpeg';
        $qrCodePath  = $this->getSaveFile($buildQcodoRes['data'],$path,$file);
        if (empty($qrCodePath)) {
            $result['success'] = false;
            $result['message'] = '图片获取失败';
            return $result;
        } 
        // 背景图
        $bgImgPath = 'data/upload/productShare/background/sharemerchantbg.jpg';
       
        $shareStream      = $this->createShareImage($bgImgPath, $qrCodePath, $productImg, $title);
        if(empty($shareStream)){
            $result['success'] = false;
            $result['message'] = '图片获取失败';
            return $result;
        }
        $path = 'data/upload/productShare/' . date('ymd') . '/shareImg/';
        $file = $path . uniqid() . '.jpeg';
        $shareUrl  = $this->getSaveFile($shareStream,$path,$file);
        $result['url'] = $shareUrl;
        @unlink($qrCodePath);
        return $result;
    }

    /**
     * 小程序图片
     * @param string $path          跳转地址
     * @param string $accessToken   微信token
     * @param int    $width         二维码宽度
     * @return array
     */
    private function createWxaCode($path = '', $accessToken = '', $width = 200)
    {
        $url      = "https://api.weixin.qq.com/wxa/getwxacode?access_token=$accessToken";
        $result   = [
            'success' => true,
            'data'    => '',
            'msg'     => ''
        ];
        $data     = [
            'path'  => $path,
            'width' => $width,
        ];
        $resource = CurlService::callWebServer($data, $url, 'POST');
        if (false == $resource['status']) {
            $result['success'] = false;
            $result['msg'] = $resource['msg'];
            return $result;
        }
        
        if(isset($resource['data']['errcode'])){
            $result['success'] = false;
            $result['msg'] = $resource['data']['errmsg'];
            return $result;
        }       
        $result['data'] =  $resource['data'];
        return $result;
    }

    /**
     * 创建分享商品图片
     * @param $bgImgPath            string 背景图片
     * @param $qrCodePath           string 二维码图片
     * @param $title                string 主题文字
     * @param $productImgPath       string 主体图片
     * @return string
     */
    private function createShareImage($bgImgPath, $qrCodePath, $productImgPath, $title)
    {
        //打开背景图
        //判断图片资源类型并创建对应图片资源
        $info = getimagesize($bgImgPath);
        if(!empty($info)){
            switch ($info[2]) {
                case 1:
                    $image = imagecreatefromgif($bgImgPath);
                    break;
                case 2:
                    $image = imagecreatefromjpeg($bgImgPath);
                    break;
                case 3:
                default:
                    $image = imagecreatefrompng($bgImgPath);
                    break;
            }
        }else{
            $res = $this->getUrl($bgImgPath);
            if (false == $res)
                return false;
    
            $image = imagecreatefromstring($res);
        }
        
        //定义画笔颜色
        $gray = imagecolorallocate($image, 153, 153, 153);
        $pink = imagecolorallocate($image, 205, 66, 61);
        //imagefill($image,0,0,$white);//为画布填充背景颜色

        //输出文字(文件必须为绝对路径)
        $font = APP_PATH . '../public/font/HiraginoSansGB-W3.otf';
        //输出字符到背景图
        $title = $this->handleTitle($title);
        ImageTTFText($image, 25, 0, 400, 650, $pink, $font, $title);
        ImageTTFText($image, 25, 0, 400, 700, $gray, $font, '长按识别小程序');

        //添加商品图片
        $productWidth  = 750;
        $productHeight = 360;
        $productImg    = $this->scaleImage($productImgPath, $productWidth, $productHeight);
        if (false == $productImg) {
            imagedestroy($image);
            return false;
        }
        imagecopymerge($image, $productImg, 0, 120, 0, 0, $productWidth, $productHeight, 100);

        //添加二维码图片
        $qrWidth = 220;
        $qrImage = $this->scaleImage($qrCodePath, $qrWidth);
        if (false == $qrImage) {
           imagedestroy($image);
           imagedestroy($productImg);
           return false;
        }
        imagecopymerge($image, $qrImage, 130, 550, 0, 0, 220, 220, 100);

        // 生成圆角图片
        // $image = $this->radiusImg($image,750,820);

        //输出图片字节流
        ob_end_clean();
        ob_start();
        imagepng($image);
        $imgStream = ob_get_contents();
        ob_end_clean();

        //销毁图像释放资源
        imagedestroy($productImg);
        imagedestroy($qrImage);
        return $imgStream;
    }
    
    /**
     * 生成圆角图片
     * @param source  $src_img 原图资源
     * @param     $width
     * @param     $height
     * @param int $radius
     * @return false|resource
     */
    private function radiusImg($src_img, $width, $height, $radius = 15)
    {
        $w = &$width;
        $h = &$height;
        // $radius = $radius == 0 ? (min($w, $h) / 2) : $radius;
        $img = imagecreatetruecolor($w, $h);
        imagesavealpha($img, true);
        //拾取一个完全透明的颜色,最后一个参数127为全透明
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);
        $r = $radius; //圆 角半径
        for ($x = 0; $x < $w; $x++) {
            for ($y = 0; $y < $h; $y++) {
                $rgbColor = imagecolorat($src_img, $x, $y);
                if (($x >= $radius && $x <= ($w - $radius)) || ($y >= $radius && $y <= ($h - $radius))) {
                    //不在四角的范围内,直接画
                    imagesetpixel($img, $x, $y, $rgbColor);
                } else {
                    //在四角的范围内选择画
                    //上左
                    $y_x = $r; //圆心X坐标
                    $y_y = $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    //上右
                    $y_x = $w - $r; //圆心X坐标
                    $y_y = $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    //下左
                    $y_x = $r; //圆心X坐标
                    $y_y = $h - $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    //下右
                    $y_x = $w - $r; //圆心X坐标
                    $y_y = $h - $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                }
            }
        }
        return $img;
    }

    /**
     * 固定图片的长宽
     * @param        $path
     * @param        $needWidth
     * @param string $needHeight
     * @return false|resource
     */
    private function scaleImage($path, $needWidth, $needHeight = '')
    {
        //判断图片资源类型并创建对应图片资源
        //获取图片的基本信息
        $info = getimagesize($path);
        if(!empty($info)){
            switch ($info[2]){
                case 1:
                    $image = imagecreatefromgif($path);
                    break;
                case 2:
                    $image = imagecreatefromjpeg($path);
                    break;
                case 3:
                default:
                    $image = imagecreatefrompng($path);
                    break;
            }
        }else{
            $res = $this->getUrl($path);
            if (false == $res)
                return false;
    
            //判断图片资源类型并创建对应图片资源
            //获取图片的基本信息
            $image = imagecreatefromstring($res);
            $info = [imagesx($image), imagesy($image)];
        }
        
        //获取宽度
        $width = $info[0];
        //获取高度
        $height = $info[1];
        if ($needHeight) {
            $newImage = imagecreatetruecolor($needWidth, $needHeight);
            $sWidth   = $needWidth;
            $sHeight  = $needHeight;
        } else {
            //计算缩放比例
            $scale = ($needWidth / $width) > ($needWidth / $height) ? $needWidth / $height : $needWidth / $width;
            //计算缩放后的尺寸
            $sWidth  = floor($width * $scale);
            $sHeight = floor($height * $scale);
            //创建目标图像资源
            $newImage = imagecreatetruecolor($sWidth, $sHeight);
        }

        imagecopyresampled($newImage, $image, 0, 0, 0, 0, $sWidth, $sHeight, $width, $height);
        imagedestroy($image);
        return $newImage;
    }

    /**
     * 商品名称长度限制
     * @param $title
     * @return false|string
     */
    private function handleTitle($title)
    {
        if (mb_strlen($title) > 10) {
            $title = mb_substr($title, 0, 10);
            $title .= '...';
        }
        return $title;
    }
   
    private function getUrl($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 $output;
    }

    private function getSaveFile($resource,$dir = '',$saveName = ''){
        if(empty($resource)){
            return false;
        }
        if(empty($dir)){
            $dir = 'upload/'.date('Y-m-d').'/';
        }
        if(!file_exists($dir)){
            mkdir($dir,true,0755);
        }
        if(empty($saveName)){
            $saveName = uniqid().'.png';
        }
        $boolean = file_put_contents($dir.$saveName,$resource);
        return $boolean ? $dir. $saveName : false;
    }
}

使用

use Tools\WxShareService;
$code = '';
$title = '';
$productImg = '';
$res = WxShareService::wxShareImg($code,$title,$productImg);
标签: PHP, 接口, 服务器

非特殊说明,本博所有文章均为博主原创。

评论啦~