PHP micro-Credit App payment method _php Tips

Source: Internet
Author: User
Tags flock getmessage md5 hash rfc sha1 sprintf string format urlencode

This article describes the micro-credit platform mobile application integrated micro-credit payment function. Share to everyone for your reference. The specific analysis is as follows:

The Wechatapppay file code is as follows:

Copy Code code as follows:

<?php
namespace Common\services\wechatpay;
Class Wechatapppay extends Wechatpaybase
{
Package parameters
Public $package = [];
Asynchronous Notification parameters
Public $notify = [];
Push pre-payment order parameters
protected $config = [];
Files that store access token and get time
protected $file;
Access token
protected $accessToken;
Fetch URL for access token
Const ACCESS_TOKEN_URL = ' https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s& secret=%s ';
Generate a pre-payment order submission Address
Const POST_ORDER_URL = ' https://api.weixin.qq.com/pay/genprepay?access_token=%s ';
Public Function __construct ()
{
$this->file = __dir__. '/payaccesstoken.txt ';
}
/**
* Create app Payment final return parameters
* @throws \exception
* @return multitype:string NULL
*/
Public Function Createapppaydata ()
{
$this->generateconfig ();
$prepayid = $this->getprepayid ();
try{
$array = [
' AppID ' => $this->appid,
' Appkey ' => $this->paysignkey,
' Noncestr ' => $this->getrandomstr (),
' Package ' => ' Sign=wxpay ',
' Partnerid ' => $this->partnerid,
' Prepayid ' => $prepayid,
' Timestamp ' => (string) time (),
];
$array [' sign '] = $this->sha1sign ($array);
unset ($array [' Appkey ']);
catch (\exception $e) {
throw new \exception ($e->getmessage ());
}
return $array;
}
/**
* Verify the notification parameters after successful payment
*
* @throws \exception
* @return Boolean
*/
Public Function verifynotify ()
{
try{
$STAYSIGNSTR = $this->notify;
unset ($staySignStr [' sign ']);
$sign = $this->signdata ($STAYSIGNSTR);
return $this->notify[' sign '] = = = $sign;
catch (\exception $e) {
throw new \exception ($e->getmessage ());
}
}
/**
* Magic method, to add payment parameters to come in
*
* @param string $name parameter name
* @param string $value parameter values
*/
Public Function __set ($name, $value)
{
$this-> $name = $value;
}
/**
* Set access token
* @param string $token
* @throws \exception
* @return Boolean
*/
Public Function Setaccesstoken ()
{
try{
if (!file_exists ($this->file) | | |!is_file ($this->file)) {
$f = fopen ($this->file, ' a ');
Fclose ($f);
}
$content = file_get_contents ($this->file);
if (!empty ($content)) {
$info = Json_decode ($content, true);
if (Time ()-$info [' GetTime '] < 7150) {
$this->accesstoken = $info [' Accesstoken '];
return true;
}
}
The contents of the file are empty or access token is invalidated and retrieved
$this->outputaccesstokentofile ();
catch (\exception $e) {
throw new \exception ($e->getmessage ());
}
return true;
}
/**
* Write access token to file
* @throws \exception
* @return Boolean
*/
protected function Outputaccesstokentofile ()
{
try{
$f = fopen ($this->file, ' WB ');
$token = [
' Accesstoken ' => $this->getaccesstoken (),
' GetTime ' => time (),
];
Flock ($f, LOCK_EX);
Fwrite ($f, Json_encode ($token));
Flock ($f, lock_un);
Fclose ($f);
$this->accesstoken = $token [' Accesstoken '];
catch (\exception $e) {
throw new \exception ($e->getmessage ());
}
return true;
}
/**
* Fetch access token
*
* @throws \exception
* @return String
*/
protected function Getaccesstoken ()
{
$url = sprintf (Self::access_token_url, $this->appid, $this->appsecret);
$result = Json_decode ($this->geturl ($url), true);
if (Isset ($result [' Errcode '])) {
throw new \exception ("Get access token failed:{$result [' ErrMsg ']}");
}
return $result [' Access_token '];
}
/**
* Take the pre-payment session identification
*
* @throws \exception
* @return String
*/
protected function Getprepayid ()
{
$data = Json_encode ($this->config);
$url = sprintf (self::P ost_order_url, $this->accesstoken);
$result = Json_decode ($this->posturl ($url, $data), true);
if (Isset ($result [' Errcode ']) && $result [' Errcode ']!= 0) {
throw new \exception ($result [' errmsg ']);
}
if (!isset ($result [' Prepayid '])) {
throw new \exception (' Get Prepayid failed, url request error. ');
}
return $result [' Prepayid '];
}
/**
* Assembly Pre-payment parameters
*
* @throws \exception
*/
protected function Generateconfig ()
{
try{
$this->config = [
' AppID ' => $this->appid,
' Traceid ' => $this->traceid,
' Noncestr ' => $this->getrandomstr (),
' Timestamp ' => time (),
' Package ' => $this->generatepackage (),
' Sign_method ' => $this->sign_method,
];
$this->config[' app_signature '] = $this->generatesign ();
catch (\exception $e) {
throw new \exception ($e->getmessage ());
}
}
/**
* Generate Package Field
*
* Generate rule:
* 1, the value of generating sign Signvalue
* 2, the package parameters are spliced again into the query string, the value needs to be UrlEncode
* 3, the Sign=signvalue stitching to 2 generated string after the final package string
*
* 2nd Step UrlEncode space needs to be encoded into%20 instead of +
*
* RFC 1738 will encode the space as +
* RFC 3986 will encode the space into%20
*
* @return String
*/
protected function Generatepackage ()
{
$this->package[' sign '] = $this->signdata ($this->package);
Return Http_build_query ($this->package, ', ' & ', php_query_rfc3986);
}
/**
* Generate signature
*
* @return String
*/
protected function Generatesign ()
{
$signArray = [
' AppID ' => $this->appid,
' Appkey ' => $this->paysignkey,
' Noncestr ' => $this->config[' noncestr '],
' Package ' => $this->config[' package '],
' Timestamp ' => $this->config[' timestamp '],
' Traceid ' => $this->traceid,
];
return $this->sha1sign ($signArray);
}
/**
* Signature Data
*
* Generate rule:
* 1, dictionary sorting, stitching into the query string format, do not need urlencode
* 2, the last step to get the string final stitching on the Key=paternerkey
* 3, MD5 hash string and convert to uppercase to get sign value Signvalue
*
* @param array $data pending signature data
* @return String Final signature result
*/
protected function SignData ($data)
{
Ksort ($data);
$str = $this->arraytostring ($data);
$str. = "&key={$this->partnerkey}";
Return Strtoupper ($this->signmd5 ($STR));
}
/**
* SHA1 Signature
* Signature Rules
* 1, dictionary sorting
* 2, stitching query string
* 3, SHA1 operation
*
* @param array $arr
* @return String
*/
protected function Sha1sign ($arr)
{
Ksort ($arr);
Return SHA1 ($this->arraytostring ($arr));
}
}

I hope this article will help you with your PHP program design.

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.