---
title: "Perl获取微信小程序二维码"
author: "lzqustc"
date: "2017-10-17T11:50:34Z"
tags: ["Perl"]
categories: ["移动开发"]
slug: "perl"
draft: false
lastmod: "2017-10-17T17:32:22Z"
id: 2396586
url: "https://lzqustc.iteye.com/blog/2396586"
---

微信小程序API：

[https://mp.weixin.qq.com/debug/wxadoc/dev/api/qrcode.html](https://mp.weixin.qq.com/debug/wxadoc/dev/api/qrcode.html)

 

\# 参数 $path即页面路径，比如："pages/index?query=1"

sub get\_wxa\_code {

    my ($fid, $path) = @\_;

 

    my $ret = **get\_access\_token();**  **#获取access\_token**

    my $image\_fid = "";

    my $json = JSON-&gt;new();

    if (length($ret-&gt;{access\_token})) {

        my $post\_data;

        $post\_data-&gt;{path} = $path;

        #$post\_data-&gt;{width} = 430;

        #$post\_data-&gt;{auth\_color} = 1;

        #$post\_data-&gt;{line\_color} = {"r"=&gt;"0","g"=&gt;"0","b"=&gt;"0"};

 

        my $param\_json\_str =$json-&gt;encode($post\_data);

        my $header = HTTP::Headers-&gt;new( Content\_Type =&gt; 'application/json; charset=utf8', );

        my $http\_request = HTTP::Request-&gt;new( POST =&gt; "https://api.weixin.qq.com/wxa/getwxacode?access\_token=".$ret-&gt;{access\_token}, $header, $param\_json\_str );

        my $ua = LWP::UserAgent-&gt;new(ssl\_opts =&gt; { verify\_hostname =&gt; 0, SSL\_verify\_mode =&gt; 0x00 });

        $ua-&gt;timeout(3);

        my $response = $ua-&gt;request($http\_request);

        if ($response-&gt;message ne "OK" && $response-&gt;is\_success ne "1") { #出错，或者timeout了

                return "timeout";

        } else { **# 如果成功，则返回的是图片对应的二进制内容，这里直接写到文件保存**

                my $file = "/var/www/wechat/files/".$fid;   #目录要有读写权限

                open(LOCAL, "&gt;$file");

                binmode(LOCAL); #内容为二进制格式

                print LOCAL $response-&gt;content();

                close LOCAL;

                if (-s $file ) { #判断是否写成功

                        $image\_fid = $fid;

                } else {

                        return "write file failed";

                }

        }

    } else {

        return "get access\_token failed";

    }

    return $image\_fid;

}