Table of Contents
回复内容:
Home Backend Development PHP Tutorial 支付宝SDK怎么用啊?

支付宝SDK怎么用啊?

Jun 06, 2016 pm 08:15 PM
php Alipay

支付宝SDK使用说明

支付宝SDK说明

<code>$c = new AopClient;
$c->gatewayUrl = "https://openapi.alipay.com/gateway.do";
$c->appId = "app_id";
$c->privateKey = "your private_key";
$c->format = "json";
$c->charset= "GBK";
$c->alipayPulicKey = "alipay_public_key";
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.open.public.template.message.industry.modify
$req = new AlipayOpenPublicTemplateMessageIndustryModifyRequest();
//SDK已经封装掉了公共参数,这里只需要传入业务参数
//此次只是参数展示,未进行字符串转义,实际情况下请转义
$request->bizContent = "{
    "primary_industry_name":"IT科技/IT软件与服务",
    "primary_industry_code":"10001/20102",
    "secondary_industry_code":"10001/20102",
    "secondary_industry_name":"IT科技/IT软件与服务"
  }"
$response= $c->execute($req);</code>
Copy after login
Copy after login

但是总是返回 缺少签名参数,有没有详细的接口说明?

回复内容:

支付宝SDK使用说明

支付宝SDK说明

<code>$c = new AopClient;
$c->gatewayUrl = "https://openapi.alipay.com/gateway.do";
$c->appId = "app_id";
$c->privateKey = "your private_key";
$c->format = "json";
$c->charset= "GBK";
$c->alipayPulicKey = "alipay_public_key";
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.open.public.template.message.industry.modify
$req = new AlipayOpenPublicTemplateMessageIndustryModifyRequest();
//SDK已经封装掉了公共参数,这里只需要传入业务参数
//此次只是参数展示,未进行字符串转义,实际情况下请转义
$request->bizContent = "{
    "primary_industry_name":"IT科技/IT软件与服务",
    "primary_industry_code":"10001/20102",
    "secondary_industry_code":"10001/20102",
    "secondary_industry_name":"IT科技/IT软件与服务"
  }"
$response= $c->execute($req);</code>
Copy after login
Copy after login

但是总是返回 缺少签名参数,有没有详细的接口说明?

第一个:支付宝SDK在Laravel5封装包 :https://github.com/Latrell/Alipay
第二个:sdk单文件

<code><?php /**
 * 支付宝集成类,根据支付宝提供的demo制作
*
 * @example
 * 创建支付请求
 * $params = []; //支付宝文档中所需的全部参数
 * $alipay = new Alipay();
 * $alipay->key = ''; //交易安全校验码
 * $this->alipay->alipay_config = $params;
 * $alipay->buildRequest();
*
 * 验证异步通知
 * $this->alipay->key = ''; //交易安全校验码
 * $this->alipay->alipay_config = $data; //支付宝异步通知参数
 * $this->alipay->verifyNotify();
*
 * @package Alipay
 * @author Dyllen
 * @since Version 0.2
*/
class Alipay {
/**
 * 交易安全校验码
*
 * @access public
 * @var string
*/
public $key;

/**
 * 请求参数配置,支付宝接口文档中所需的参数
*
 * @access public
 * @var array
*/
public $alipay_config=[];

/**
 * HTTPS证书,用于cURL
 * 默认和本类文件同级目录的cacert.pem文件
*
 * @access public
 * @var string
*/
public $credential;

/**
 * 支付宝网关地址
*/
const ALIPAY_GATEWAY = 'https://mapi.alipay.com/gateway.do?';

/**
 * HTTPS形式消息验证地址
*/
const HTTPS_VERIFY_URL = 'https://mapi.alipay.com/gateway.do?service=notify_verify&';

/**
 * HTTP形式消息验证地址
*/
const HTTP_VERIFY_URL = 'http://notify.alipay.com/trade/notify_query.do?';

/**
 * 创建支付请求,重定向到支付宝收银台
*
 * @access public
 * @return void
*/
public function buildRequest() {
$this->alipay_config['sign'] = $this->signData();
return self::ALIPAY_GATEWAY . $this->createQueryString('', true);
}

/**
 * 验证支付宝异步通知参数合法性
*
 * @access public
 * @return boolean
*/
public function verifyNotify() {
$param_tmp = $this->filter(); //过滤待签名数据
$responseTxt = 'true';
if( !empty( $this->alipay_config['notify_id'] ) ) {
$responseTxt = $this->getResponse();
}
if($this->alipay_config['sign_type'] == 'RSA') {
$signString = $this->getSignString();
$ci = & get_instance();

//初始化RSA库
$ci -> load -> library('rsa');
return $ci->rsa->verifySign($signString, base64_decode($this->alipay_config['sign']), $ci->config->item('alipay_public_key'));
}
else {
$sign = $this->signData();
if ( preg_match("/true$/i",$responseTxt) && ($sign == $this->alipay_config['sign']) ) {
return true;
} else {
return false;
}
}
}

/**
 * 签名数据
 * 签名规则:
 * sign和sign_type不参加签名,需要去掉
 * 对参数数组依据键名按照字母顺序升序排序
 * 排序完成之后键值对用&字符连接,组成URL的查询字符串形式待签名字符串,待签名数据不需用url encoding
 * MD5签名:私钥拼接到待签名字符串的后面,然后用md5对字符串运算,得到32位签名结果
*
 * @return string 已签名数据
*/
private function signData() {
$param_tmp = $this->getSignString(); //待签名字符串

if( !isset($this->key) ) {
return FALSE;
}

$sign = '';

//签名数据
switch ($this->alipay_config['sign_type']) {
case 'RSA':
$sign = $this->rsaSign($param_tmp);
break;
case 'DES':
break;
default:
$sign = $this->md5Sign($param_tmp);
}

return $sign;
}

/**
 * MD5加密字符串
*
 * @access private
 * @param string $data 待加密字符串
 * @return string
*/
private function md5Sign( $data ) {
return md5($data . $this->key);
}

/**
 * RSA 加密字符串
*
 * @param string $data 待加密字符串
 * @return string
*/
private function rsaSign( $data ) {
$ci = & get_instance();
//初始化RSA库
$ci -> load -> library('rsa');
$ci -> rsa -> setKey($ci -> config -> item('pay_private_key'), $ci -> config -> item('pay_public_key'));
return $ci->rsa->encrypt($data);
}

/**
 * 获得待签名数据
*
 * @access private
 * @return string
*/
private function getSignString() {
$param_tmp = $this->filter(); //过滤待签名数据

//排序
ksort($param_tmp);
reset($param_tmp);

//创建查询字符串形式的待签名数据
return $this->createQueryString($param_tmp);
}

/**
 * 过滤待签名数据,去掉sing、sing_type及空值
*
 * @access private
 * @return array
*/
private function filter() {
$para_filter = array();
foreach($this->alipay_config as $key => $value){
if($key =="sign"|| $key =="sign_type"|| empty($value)) continue;
else $para_filter[$key] = $value;
}
return $para_filter;
}

/**
 * 用&拼接字符串,形成URL查询字符串
*
 * @access private
 * @param array $data
 * @param boolean $is_encode 是否对值做urlencode
 * @return string
*/
private function createQueryString($data=NULL, $is_encode=false ) {
$arr = empty($data) ? $this->alipay_config : $data;
$arg = '';
foreach( $arr as $key => $value ) {
if($is_encode) {
$key = urlencode($key);
$value = urlencode($value);
}
$arg .= $key . '=' . $value . '&';
}
$arg = substr($arg, 0, strlen($arg)-1); //去掉最后一个&
//如果存在转义字符,那么去掉转义
if(get_magic_quotes_gpc()) {$arg = stripslashes($arg);}

return $arg;
}

/**
 * 获取远程服务器ATN结果,验证返回URL
*
 * 验证结果集:
 * invalid命令参数不对 出现这个错误,请检测返回处理中partner和key是否为空
 * true 返回正确信息
 * false 请检查防火墙或者是服务器阻止端口问题以及验证时间是否超过一分钟
*
 * @access private
 * @return 服务器ATN结果
*/
private function getResponse() {
//载入支付配置
$ci = & get_instance();
$ci->config->load('alipay');
$config = $ci->config->item('alipay');

$transport = strtolower(trim($config['transport']));
$partner = trim($config['partner']);
$veryfy_url = '';
if($transport == 'https') {
$veryfy_url = self::HTTPS_VERIFY_URL;
}
else {
$veryfy_url = self::HTTP_VERIFY_URL;
}
$veryfy_url = $veryfy_url."partner=". $partner ."&notify_id=". $this->alipay_config['notify_id'];
$responseTxt = $this->getHttpResponseGET($veryfy_url);

return $responseTxt;
}

/**
 * 取证书,用于cURL的请求
*
 * @access private
 * @return string 证书路径
*/
private function getCr() {
if( ! empty($this->credential) ) {
return $this->credential;
}
return getcwd() . DIRECTORY_SEPARATOR . 'applicationlibraries' . DIRECTORY_SEPARATOR .'cacert.pem';
}

/**
 * 远程获取数据,POST模式
 * 注意:
 * 1.使用Crul需要修改服务器中php.ini文件的设置,找到php_curl.dll去掉前面的";"就行了
 * 2.文件夹中cacert.pem是SSL证书请保证其路径有效,目前默认路径是:getcwd().'\cacert.pem'
*
 * @param $url 指定URL完整路径地址
 * @param $cacert_url 指定当前工作目录绝对路径
 * @param $para 请求的数据
 * @param $input_charset 编码格式。默认值:空值
 * return 远程输出的数据
*/
private function getHttpResponsePOST($url, $para, $input_charset = '') {

if (trim($input_charset) != '') {
$url = $url."_input_charset=".$input_charset;
}
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
curl_setopt($curl, CURLOPT_CAINFO,$this->getCr());//证书地址
curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
curl_setopt($curl, CURLOPT_POST,true); // post传输数据
curl_setopt($curl, CURLOPT_POSTFIELDS,$para);// post传输数据
$responseText = curl_exec($curl);
//var_dump( curl_error($curl) );//如果执行curl过程中出现异常,可打开此开关,以便查看异常内容
curl_close($curl);

return $responseText;
}

/**
 * 远程获取数据,GET模式
 * 注意:
 * 1.使用Crul需要修改服务器中php.ini文件的设置,找到php_curl.dll去掉前面的";"就行了
 * 2.文件夹中cacert.pem是SSL证书请保证其路径有效,目前默认路径是:getcwd().'\cacert.pem'
*
 * @param $url 指定URL完整路径地址
 * @param $cacert_url 指定当前工作目录绝对路径
 * return 远程输出的数据
*/
private function getHttpResponseGET($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
curl_setopt($curl, CURLOPT_CAINFO,$this->getCr());//证书地址
$responseText = curl_exec($curl);
//var_dump( curl_error($curl) );exit;//如果执行curl过程中出现异常,可打开此开关,以便查看异常内容
curl_close($curl);

return $responseText;
}
}
/**
 * 支付宝配置文件
*/
$config['alipay'] = array(
 'key' => 'XXXX', //交易安全校验码,用于签名的32位密钥
 'transport' => 'https', //消息验证地址使用访问方式
 'seller_email' => 'XXXX', //卖家支付宝账号,即收款账户

 'service' => 'create_direct_pay_by_user', //接口名称
 'partner' => '2343546', //合作者省份ID
 '_input_charset' => 'utf-8', //参数编码字符集
 'sign_type' => 'MD5', //签名方式,不参加签名
 'notify_url' => '2324343', //服务器异步通知页面路径
 'return_url' => '3435465768', //页面跳转通知页面路径
);
//异步通知例子,CI框架
//载入支付配置
$this->config->load('alipay');
$this->load->library('Alipay');

$this->alipay->key = $this->config->item('alipay')['key'];
$this->alipay->alipay_config = $data; //这个data是支付宝提交过来的参数

if( ! $this->alipay->verifyNotify() ) {
 echo 'fail';exit;
}</code>
Copy after login

第三个我写的:这些你够用了 我写的太乱了就不发了 有问题留言

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

See all articles