Alipay Service Window API Interface development PHP version _php instance

Source: Internet
Author: User
Tags curl openssl php class

Alipay Service Window API interface development for many sites to recharge friends is very important, today we will look at a PHP version of the Payment Service Window API interface development examples.

These two days have nothing to connect to pay Treasure service window, see Pay Treasure Demo, my God, how do I evaluate good? Reading is not very good, it is a hindrance to simple development. So I based on the API to provide a simple development point, the interface is still a lot of imperfect, interested can improve their own, the bottom I put the code posted out, have time to write how to use.

<?php class alipayservice{/**-Service Interface Information */public $service = null; 
 /**-Signature Information */public $sign = null; 
 /**-Signature Type */public $sign _type = null; 
 /**-Character Set/public $charset = null; 
 /**-Parsed biz_content data */public $request = null; 
 /**-User OpenID */public $from _user_id = null; 
 /**-Message Type */public $msg _type = null; 
 /**-Event Type/public $event _type = null; 
 /**-Behavioral Parameters */public $action _param = null; 
 /**-Alipay User information */public $user _info = null; 
 /**-Text message content */public $text = null; 
 /**-Image Media ID */public $media _id = null; 
 /**-Picture Format */public $format = null; 
 /**-Open Debugging/private $debug = false; /**-Interface type/private $interface _type = Array (' QRCode ' => ' alipay.mobile.public.qrcode.create ', ' follow ' = > ' alipay.mobile.public.follow.list ', ' gis_get ' => ' alipay.mobile.public.gis.get ', ' menu_get ' => ' Bile.public.menu.get ', ' Menu_add '=> ' Alipay.mobile.public.menu.add ', ' Down_media ' => ' alipay.mobile.public.multimedia.download ', ' menu_update '  => ' alipay.mobile.public.menu.update ', ' info_query ' => ' alipay.mobile.public.info.query ', ' info_modify ' => ' Alipay.mobile.public.info.modify ', ' shortlink ' => ' alipay.mobile.public.shortlink.create ', ' label_add ' => ' a Lipay.mobile.public.label.add ', ' Label_del ' => ' alipay.mobile.public.label.delete ', ' label_update ' => '. Mobile.public.label.update ', ' label_query ' => ' alipay.mobile.public.label.query ', ' label_user_add ' => ' . Mobile.public.label.user.add ', ' Label_user_del ' => ' alipay.mobile.public.label.user.delete ', ' Label_user_ Query ' => ' alipay.mobile.public.label.user.query ', ' message_custom ' => ' Alipay.mobile.public.message.custom.send ', ' message_total ' => ' alipay.mobile.public.message.total.send ', ' Message_single ' => ' alipay.mobile.public.message.single.send ', ' Message_laBel_send ' => ' alipay.mobile.public.message.label.send ',); 
 /**-Private key address, replace it with your own * * Private $private _rsa_key_path = ' Rsa_private_key.pem '; 
 /**-Private key address, replace it with your own * * Private $public _rsa_key_path = ' Rsa_public_key.pem '; 
 /**-the app ID of the Alipay window is replaced with your own * * Private $app _id = ' 2015120200901652 '; /**-Turn on debug Parameters-@params bool Debug true turn debugging false off debugging-@author Widuu <admin@widuu.com>/public func 
 tion __construct ($debug = False) {/* Open Debug/if ($debug) $this->debug = true; /**-Gets the parameter, resolves the request parameter--@author widuu <admin@widuu.com>/* Public Function get_request () {if (!emptyem 
  Pty ($_post)) {//Requested service interface $this->service = $_post[' service ']; 
  Gets the request character set $this->charset = $_post[' CharSet ']; 
  Obtain the requested biz_content $request _biz_content = $_post[' biz_content ']; 
  Encryption algorithm $this->sign_type = $_post[' Sign_type ']; 
  Encrypted string $this->sign = $_post[' sign ']; If the request format is not a Utf-8 conversion format of Utf-8 if (strtolowER ($this->charset)!= ' Utf-8 ') {$request _biz_content = iconv (' GBK ', ' utf-8 ', $request _biz_content); 
  }//parsing string is XML $request _xml = @simplexml_load_string ($request _biz_content, "SimpleXMLElement", libxml_nocdata); 
  Resolves an array $request _array = Json_decode (Json_encode ($request _xml), true); 
  $this->request = $request _array; 
  * * Analytical/$this->analysis ($request _array); 
  if ($this->debug) $this->write_log (' Request_info ', Var_export ($request _array,true)); 
  The default authentication method if ($this->service = = ' Alipay.service.check ') {$this->verify ($_post); 
  Exit (); 
 /* Returns the result * * return $request _array; }/**-Reply text content-@params string content text data-@params bool mass ture for mass-@author Widuu <admin@widuu.com 
 > */Public Function text ($content, $mass =false) {$info [' text '] = array (' content ' => $content); 
 /* Organization Content * * $biz _content = $this->common_response (' text ', $info, $mass); /* To determine whether the mass/if ($mass) {$method = ' message_total '; 
 }else{$method = ' message_custom '; 
 $sys _params = $this->common_system ($method, $biz _content); 
 $sys _params[' sign '] = $this->rsa_sign ($this->build_query ($sys _params)); 
 /* Returns the result is JSON data * * * $result = $this->response_post ($sys _params); 
 return $result; /**-Reply Graphic Content-@params array articles concatenation of the text message arrays-@params bool mass ture for mass-@author Widuu <admin@widuu.co 
 m> */Public function articles ($articles, $mass =false) {$info [' articles '] = array ($articles); 
 /* Organization Content * * $biz _content = $this->common_response (' Image-text ', $info, $mass); 
 /* To determine whether the mass/if ($mass) {$method = ' message_total '; 
 }else{$method = ' message_custom '; 
 }/* Encryption parameters//$sys _params = $this->common_system ($method, $biz _content); 
 /* Encrypted character//$sys _params[' sign '] = $this->rsa_sign ($this->build_query ($sys _params)); 
 /* Returns the result is JSON data * * * $result = $this->response_post ($sys _params); 
 return $result; /**-Attention Event-@author Widuu <admin@widuu.com> */Public Function Is_follow () {$request = $this->request; 
 if ($request [' msgtype '] = = ' event ' && $request [' eventtype '] = = ' follow ') {return true; 
 }else{return false; }/**-Cancel the attention event-@author widuu <admin@widuu.com>/Public Function Is_unfollow () {$request = $t 
 his->request; 
 if ($request [' msgtype '] = = ' event ' && $request [' eventtype '] = = ' unfollow ') {return true; 
 }else{return false; }/**-Download user's picture-@param media_id string picture id-@param filename string save picture address and name-@author Widuu <admin @widuu .com> */Public Function Down_media ($media _id, $filename) {$sys _params = $this->common_system (' Down_media 
 ', Array (' MediaId ' => $media _id)); 
 $sys _params[' sign '] = $this->rsa_sign ($this->build_query ($sys _params)); 
 /* Return Data * * * $result = $this->response_post ($sys _params,true); 
 $result = File_put_contents ($filename, $result); if ($this->debug) {$thiS->write_log (' Save_image ', ' Save Picture '. 
 string) $result); 
 return $result; /**-(add | update | get) custom menu-@param string $type (add|update|get)-@param array $menu menu, if the Fetch menu can be left blank-@author W Iduu <admin@widuu.com>/Public Function menu ($type, $menu = Array ()) {if!in_array ($type, Array ("Get", ' Up 
  Date ', ' add ') {if ($this->debug) {$this->write_log (' Error ', ' Menu action method error '); 
 return false; 
 /* Stitching Interface Method * * $method = ' menu_ '. $type; 
 $sys _params = $this->common_system ($method, $menu); 
 /* Encrypted string/$sys _params[' sign '] = $this->rsa_sign ($this->build_query ($sys _params)); 
 /* Request FETCH RESULT * * * $result = $this->response_post ($sys _params); 
 /* Escape and Parse JSON data * * * $menu _json = Json_decode (Iconv (' GBK ', ' utf-8 ', $result), true); /* Organization INTERFACE Information * * * $interface = ' alipay_mobile_public_ '. $method. ' 
 _response '; /* encountered an error return */if ($menu _json[$interface] [' Code ']!=] {if ($this->debug) {$this->write_log (' Get_menu_err OR ', $menu _json[$interface][' msg ']); 
 return false; 
 }/* To return different results depending on type * * ($type = = ' Get ') {returns $menu _json[$interface] [' menu_content ']; 
 }else{return $menu _json[$interface] [' msg ']; }/**-Post data Method-@param array params array-@author widuu <admin@widuu.com>/Private function Response_post ($params, $type =false) {//download media and request Gateway if ($down) {$url = ' https://openfile.alipay.com/chat/multimedia.do ' 
 ; 
 }else{$url = ' https://openapi.alipay.com/gateway.do '; 
 } $ch = Curl_init (); 
 curl_setopt ($ch, Curlopt_url, $url); 
 curl_setopt ($ch, Curlopt_header, 0); 
 curl_setopt ($ch, Curlopt_returntransfer, 1); 
 curl_setopt ($ch, Curlopt_post, 1); 
 curl_setopt ($ch, Curlopt_postfields, Http_build_query ($params)); 
 curl_setopt ($ch, curlopt_followlocation,true); 
 curl_setopt ($ch, Curlopt_ssl_verifypeer, false); 
 curl_setopt ($ch, Curlopt_ssl_verifyhost, false); 
 curl_setopt ($ch, curlopt_sslversion, CURL_SSLVERSION_TLSV1); 
 $curl = curl_exec ($ch); Curl_close ($CH); 
 return $curl; /**-Stitching back data-@param string $type reply type-@param array $info reply-@param bool $mass is mass-@author Widuu 
 <admin@widuu.com> * Private Function Common_response ($type, $info, $mass =false) {$request = $this->request; 
 $params = Array (); 
 If not mass if (! $mass) $params [' touserid '] = $request [' Fromuserid ']; 
 $params [' msgtype '] = $type; 
 $params [' createtime '] = time (); 
 $content = Array_merge ($params, $info); 
 return $content;  /**-Concatenation Encryption parameter-@param string $interface _type interface type-@param array $biz _content returns the arrays of Biz_content-@author Widuu <admin@widuu.com>/Private Function Common_system ($interface _type, $biz _content) {/* Interface set/* * $type = $th 
 is->interface_type; 
 $method = $type [$interface _type]; /* Public parameters */$params = Array (' method ' => $method, ' charset ' => ' UTF-8 ', ' sign_type ' => ' RSA ', ' App_ 
  Id ' => $this->app_id, ' timestamp ' => date (' y-m-d h:i:s ', Time ()),' Version ' => ' 1.0 ',); 
 /* Get some interfaces without biz_content parameters */if (count ($biz _content) > 0) {$params [' biz_content '] = Json_encode ($biz _content); 
 /* Returns the system parameter/return $params; /**-Service Authentication-@params array params is an automatic authentication information-@author widuu <admin@widuu.com>/Private Function Veri  
  FY ($params) {/* parameter is NULL/*/if (Emptyempty ($params)) {if ($this->debug) {$this->write_log (' ERROR ', ' Validation parameter is null '); 
 }/* Build parameters, use dictionary to sort and then splice strings * * * $query _data = $this->build_query ($params); 
 /* Verify information, it is possible that PHP version bug does not support verification/$verify _result = $this->ras_verify ($query _data); /* Return validation results/if ($verify _result) {/* The string of the public key is merged into one line * * $public _rsa_string = file_get_contents ($this->public_rs 
  A_key_path); 
  $public _rsa_string = str_replace ("-----BEGIN public KEY-----", "", $public _rsa_string); 
  $public _rsa_string = str_replace ("-----End public KEY-----", "", $public _rsa_string); 
  $public _rsa_string = Str_replace ("\ R", "", $public _rsa_string); $public_rsa_string = Str_replace ("\ n", "", $public _rsa_string); /* Build encrypted string/$response _xml = "<success>true</success><biz_content> $public _rsa_string</biz_ 
  Content> "; 
  /* Generate validation information */$sign = $this->rsa_sign ($response _xml); /* Build RETURN Data * * * $response = "<?xml version=\" 1.0\ "encoding=\" gbk\ "?><alipay><response> $response _xml& 
  lt;/response><sign> $sign </sign><sign_type>RSA</sign_type></alipay> "; 
  if ($this->debug) {$this->write_log (' Check_response ', $response); 
  /* Output return information */echo $response; 
 Exit (); 
  }else{if ($this->debug) {$this->write_log (' ERROR ', ' validation failed '); }}/**-concatenation is a string function-@params array params concatenation function-@author widuu <admin@widuu.com> * Private functi 
 On Build_query ($params) {/* Delete sign string/unset ($params [' sign ']); 
 /* Dictionary Sort * * Ksort ($params); 
 /* Splicing * * * $query _array = array (); foreach ($params as $k => $v) {$query _arraY[] = "$k". " ="." 
 $v "; 
 $query _data = Implode ("&", $query _array); 
 /* Returns the string of stitching good/return $query _data; /**-Verify encryption sign, some PHP versions do not support, do not support direct return true-@params string Query_data encrypted string-@author Widuu <admin@widuu.com&gt 
 ; /Private Function Ras_verify ($query _data) {/* Read public key file, PEM format */$pubKey = file_get_contents ($this->public_rsa_key 
 _path); 
 /* Convert to OpenSSL format key//$res = Openssl_get_publickey ($pubKey); 
 /* Call OpenSSL built-in method verification * * * $result = (bool) openssl_verify ($query _data, Base64_decode ($this->sign), $res); 
 /* Release Resources * * Openssl_free_key ($res); 
 /* Some PHP version error, direct return true/if (Strpos (openssl_error_string (), ' Pem_read_bio ')) {returns true; 
 }/* Return the results of the verification * * $RESULT; /**-Encrypt data by private key-@params string Data Encryption-@author Widuu <admin@widuu.com>/Private Function Rsa_ 
 Sign ($data) {/* Read private key/$priKey = file_get_contents ($this->private_rsa_key_path); /* Convert to OpenSSL format key */$res = Openssl_get_privatekey ($priKey); 
 /* Call OpenSSL encryption * * OPENSSL_SIGN ($data, $sign, $res); 
 /* Release Resources * * Openssl_free_key ($res); 
 /* BASE64 Encryption */$sign = Base64_encode ($sign); 
 /* Return the ENCRYPTION parameter * * $SIGN; Private Function Analysis ($params) {switch ($params [' Msgtype ']) {case ' image ': $this->media_id = $params [' Im 
  Age ' [' MediaId ']; 
  $this->format = $params [' Image '] [' format ']; 
  Break 
  Case ' text ': $this->text = $params [' text '] [' Content ']; 
  Break 
  Case ' event ': $this->event_type = $params [' EventType ']; 
  $this->action_param = $params [' Actionparam ']; 
  Break 
 Default:break; 
 $this->msg_type = $params [' Msgtype ']; 
 $this->user_info = Json_decode ($params [' UserInfo '],true); /**-the concatenation string when DEBUG is true-@param string $level custom identifier-@param string $info Custom Content-@param string $log _path Self Define log path-@author widuu <admin@widuu.com>/* Public Function Write_log ($level, $info, $log _path = ') {if (emp Tyempty ($log _path)) {//PHPFEnsi.com $log _path = dirname (__file__). 
 "/log.txt"; File_put_contents ($log _path, [$level]. Date ("Y-m-d h:i:s"). " " . $info. 
 "\ r \ n", file_append);  } 
}

Okay, the above is a small series for you to organize an article on the Payment Treasure Service Window API Interface Development example, this has the prerequisite is that we have to apply for a permission can be, the official can apply for small part of the introduction.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.