微信支付分开发-使用V3接口

一、安装官方SDK

composer require wechatpay/wechatpay

二、封装

$this->config打印内容:
array:3 ["appId" => "公众号appid""appSecret" => "公众号appSecret""pay" => array:5 ["merchantId" => "商户id""key" => "商户密钥""serial" => "「商户API证书」的「证书序列号」""apiClientKey" => "D:\phpstudy_pro\WWW\test\app/extend/wechat/pay/cert/apiclient_key.pem""apiClientCert" => "D:\phpstudy_pro\WWW\test\app/extend/wechat/pay/cert/apiclient_cert.pem"]
]
config = config('app.weChat');$this->init();}public function init(){// 设置参数// 商户号$merchantId = $this->config['pay']['merchantId'];// 从本地文件中加载「商户API私钥」,「商户API私钥」会用来生成请求的签名 apiclient_key.pem文件路径$merchantPrivateKeyFilePath = 'file://'.$this->config['pay']['apiClientKey'];$merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);// 「商户API证书」的「证书序列号」$merchantCertificateSerial = $this->config['pay']['serial'];// 从本地文件中加载「微信支付平台证书」,用来验证微信支付应答的签名(去你妈的傻逼微信文档,不是下载的支付证书)
//        $platformCertificateFilePath = 'file://'.$this->config['pay']['apiClientCert'];$platformCertificateFilePath = $this->certificates();$platformPublicKeyInstance = Rsa::from($platformCertificateFilePath, Rsa::KEY_TYPE_PUBLIC);// 从「微信支付平台证书」中获取「证书序列号」$platformCertificateSerial = PemUtil::parseCertificateSerialNo($platformCertificateFilePath);// 构造一个 APIv3 客户端实例$app = Builder::factory(['mchid'      => $merchantId,'serial'     => $merchantCertificateSerial,'privateKey' => $merchantPrivateKeyInstance,'certs'      => [$platformCertificateSerial => $platformPublicKeyInstance,],]);$this->app = $app;}/*** 微信支付分:商户预授权API* @param $authorization_code string 协议号1-32位(同一个商户号下唯一)* @param $notify_url string 回调地址*/public function payScorePermissions($authorization_code,$notify_url){try {$resp = $this->app->chain('v3/payscore/permissions')->post(['json' => ['service_id'        => '500001','appid'        => $this->config['appId'],'authorization_code'        => $authorization_code,'notify_url'=>$notify_url]]);echo $resp->getStatusCode(), PHP_EOL;echo $resp->getBody(), PHP_EOL;} catch (\Exception $e) {dd($e->getMessage());
//            apiError($e->getMessage());}}/*** 获取证书* @return mixed*/public function certificates(){//请求参数(报文主体)$headers = $this->sign('GET','https://api.mch.weixin.qq.com/v3/certificates','');$result =  $this->curl_get('https://api.mch.weixin.qq.com/v3/certificates',$headers);$result = json_decode($result,true);return $this->decryptToString($result['data'][0]['encrypt_certificate']['associated_data'],$result['data'][0]['encrypt_certificate']['nonce'],$result['data'][0]['encrypt_certificate']['ciphertext']);}/*** 签名* @param string $http_method    请求方式GET|POST* @param string $url            url* @param string $body           报文主体* @return array*/public function sign($http_method = 'POST',$url = '',$body = ''){$mch_private_key =  $this->getMchKey();//私钥$timestamp = time();//时间戳$nonce =  getRands(32);//随机串$url_parts = parse_url($url);$canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));//构造签名串$message = $http_method."\n".$canonical_url."\n".$timestamp."\n".$nonce."\n".$body."\n";//报文主体//计算签名值openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');$sign = base64_encode($raw_sign);//设置HTTP头$token = sprintf('WECHATPAY2-SHA256-RSA2048 mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',$this->config['pay']['merchantId'], $nonce, $timestamp, $this->config['pay']['serial'], $sign);$headers = ['Accept: application/json','User-Agent: */*','Content-Type: application/json; charset=utf-8','Authorization: '.$token,];return $headers;}/*** 私钥* @return false|resource*/public function getMchKey(){//path->私钥文件存放路径return openssl_get_privatekey(file_get_contents($this->config['pay']['apiClientKey']));}/*** get请求* @param $url* @param array $headers* @return bool|string*/public function curl_get($url,$headers=array()){$info = curl_init();curl_setopt($info,CURLOPT_RETURNTRANSFER,true);curl_setopt($info,CURLOPT_HEADER,0);curl_setopt($info,CURLOPT_NOBODY,0);curl_setopt($info,CURLOPT_SSL_VERIFYPEER,false);curl_setopt($info,CURLOPT_SSL_VERIFYPEER,false);curl_setopt($info,CURLOPT_SSL_VERIFYHOST,false);//设置header头curl_setopt($info, CURLOPT_HTTPHEADER,$headers);curl_setopt($info,CURLOPT_URL,$url);$output = curl_exec($info);curl_close($info);return $output;}const KEY_LENGTH_BYTE = 32;const AUTH_TAG_LENGTH_BYTE = 16;/*** Decrypt AEAD_AES_256_GCM ciphertext** @param string    $associatedData     AES GCM additional authentication data* @param string    $nonceStr           AES GCM nonce* @param string    $ciphertext         AES GCM cipher text** @return string|bool      Decrypted string on success or FALSE on failure*/public function decryptToString($associatedData, $nonceStr, $ciphertext) {$aesKey = $this->config['pay']['key'];$ciphertext = \base64_decode($ciphertext);if (strlen($ciphertext) <= self::AUTH_TAG_LENGTH_BYTE) {return false;}// ext-sodium (default installed on >= PHP 7.2)if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {return \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $aesKey);}// ext-libsodium (need install libsodium-php 1.x via pecl)if (function_exists('\Sodium\crypto_aead_aes256gcm_is_available') && \Sodium\crypto_aead_aes256gcm_is_available()) {return \Sodium\crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $aesKey);}// openssl (PHP >= 7.1 support AEAD)if (PHP_VERSION_ID >= 70100 && in_array('aes-256-gcm', \openssl_get_cipher_methods())) {$ctext = substr($ciphertext, 0, -self::AUTH_TAG_LENGTH_BYTE);$authTag = substr($ciphertext, -self::AUTH_TAG_LENGTH_BYTE);return \openssl_decrypt($ctext, 'aes-256-gcm', $aesKey, \OPENSSL_RAW_DATA, $nonceStr,$authTag, $associatedData);}throw new \RuntimeException('AEAD_AES_256_GCM需要PHP 7.1以上或者安装libsodium-php');}}

三、使用

use App\extend\wechat\pay\WeChatPay;  
public function payScorePermissions(){$weChatPay = new WeChatPay();$authorization_code = getRands(20,2);$notify_url = request()->url().'NotifyUrl';$weChatPay->payScorePermissions($authorization_code,$notify_url);
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部