首先下载官方SDK
支付宝官方SDK
代码实现
<?php
namespace app\common\service;
use think\Db;
use think\Exception;
class CreateAlipayQrcodeService {
const APPID = "20210021";
const PRIVATEKEY = 'MII=';
const PUBLICKEY = 'AQAB';
public static function createQrcode($queryParam, $page = "pages/tabs/home", $describe = "默认站点",$site_id=0,$domain=false) {
include EXTEND_PATH . "alipay/AopClient.php";
include EXTEND_PATH . "alipay/request/AlipayOpenAppQrcodeCreateRequest.php";
try {
$aop = new \AopClient ();
$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
$aop->appId = self::APPID;
$rsaPrivateKey = self::PRIVATEKEY;
$aop->rsaPrivateKey = trim($rsaPrivateKey);
$alipayrsaPublicKey = self::PUBLICKEY;
$aop->alipayrsaPublicKey = trim($alipayrsaPublicKey);
$aop->apiVersion = '1.0';
$aop->signType = 'RSA2';
$aop->postCharset = 'UTF-8';
$aop->format = 'json';
$request = new \AlipayOpenAppQrcodeCreateRequest ();
$request->setBizContent("{" . "\"url_param\":\"" . $page . "\"," . "\"query_param\":\"" . $queryParam . "\"," . "\"describe\":\"" . $describe . "\"" . " }");
$result = $aop->execute($request);
$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
$resultCode = $result->$responseNode->code;
if(!empty($resultCode)&&$resultCode == 10000){
if ($domain){
return self::create($result->$responseNode->qr_code_url,$site_id);
}else{
return $result->$responseNode->qr_code_url;
}
}else{
throw new Exception("错误代码:".$resultCode);
}
} catch (Exception $exception) {
throw new Exception($exception->getMessage());
}
}
protected static function create($qr_code_url,$site_id){
$d=date("Ymd",time());
$save_dir=ROOT_PATH."public";
$dk="/alipay/".$d."/";
$save_dir.=$dk;
$filename=$site_id.".jpg";
if (!is_dir($save_dir)){
@mkdir($save_dir,0777,true);
}
if (file_exists($save_dir.$filename)){
return $dk.$filename;
}
$url=$qr_code_url.".jpg";
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt ( $ch, CURLOPT_URL, $url );
ob_start ();
curl_exec ( $ch );
$return_content = ob_get_contents();
ob_end_clean ();
$fp=@fopen($save_dir.$filename,"a");
fwrite($fp,$return_content);
fclose($fp);
return $dk.$filename;
}
}